# author: Roy.G
#1.类 和类的实例化
# class Role:
# n=100
# def __init__(self,name,role,weapon,life=100,money=10000):
# self.name=name
# self.role=role
# self.weapon=weapon
# self.life=life
# self.money=money
# def shot(self):
# print("%s got shot"%self.name)
#
# r1=Role("roy","51","52")
# r1_shot=r1.shot()
# print(r1.name,r1.n)
# r1.shot()
# Role.n=12
# print(r1.n)
# r1.n=20
# print(r1.n)
# print(Role.n)
# # for item in r1.:
# print(item)
#2. 类变量的作用及析构函数
# class person:
# cn="中国"
# def __init__(self,name,age,addr,life=100):
# self.name=name
# self.age=age
# self.addr=addr
# self.life=life
# def __del__(self):
# print("%s 运行结束了" % self.name)
# def life_left(self):
# print("life=%s,ok!"%self.life)
# def eat(self):
# print("eat meat!")
#
# roy=person("roy",18,"沈阳",90)
# # del roy #调用程序结束,就会 执行__del__,如果删除变量,就会立刻执行__del__
# # print(roy.age)
# # roy.eat="红烧肉"
# # print(roy.eat)
# # roy.__del__()
# # print("---------")
# # print(roy.eat)
# # r2=person("r2",20,"北京")
# # a=r2.eat()
# import time
# # time.sleep(3)
# print(roy.life_left())
# print("-----done-----")
# 析构函数,在实释放和结束的时候,通常做一些收尾工作:
#关闭数据库打开的临时文件,在程序运行结束,或删除变量时,执行del
# 3.私有属性,私有方法
# class Role:
# n=100
# def __init__(self,name,role,weapon,life=100,money=10000):
# self.name=name
# self.role=role
# self.weapon=weapon
# self.__life=life
# self.money=money
#
# def __life_up(self):
# self.__life += 30
# print("life up 30!")
# def shot(self):
# self.__life-=50
# print("%s got shot" % self.name, "life=%d" % self.__life)
# if self.__life < 100:
# self.__life_up()
# def left(self):
# print(self.__life)
#
# roy=Role("roy","p","ak47",100,8000)
# roy.shot()
# roy.left()
# roy.shot()
# roy.left()
# roy.shot()
# roy.left()
# roy.shot()
# roy.left()
#4.封装,继承,多态
class Father:
def __init__(self,name,tall=0):#这里初始化后,原来的父函数就丢失了
self.name=name
self.tall=tall
def p(self):
print("father")
def beat(self):
print("in the fathe def:beat")
class Friend(object): # self to object
def mkfriends(self,object):
print("%s make friend with %s"%(self.name,object.name))
class Sun(Father,Friend):
def __init__(self,name,tall,age=0):
# Father.__init__(self,name,tall) #二次初始化father,把father的属性继承给sun
super(Sun,self).__init__(name,tall) #super 的意思是上方的意思,将father的init传入sun
self.age=age
def s(self):
print("sun")
def sun_haha(self):
print("in the sun:sun_1")
class dauter(Father,Friend): #执行的顺序是从左到右
def __init__(self,name,tall=0,wt=0):
super(dauter, self).__init__(name,tall)
self.wt=wt
def eat(self):
print("dauter eating")
s1=Sun("a",100)
dt=dauter("b",100,90)
s1.mkfriends(dt)
s1.sun_haha()
# print(s1.age)
print(s1.age)
#多继承的顺序问题:多继承只运行第一个init,后界面的不会运行,这个策略叫广度优先,第二种叫深度优先
# py2的经典类是按深度优先进行继承的,新式类是按广度优先,py3,经典和新式类都是按广度优先
#5 多态:统一调用端口和 方法
#6 静态方法@staticmethod,静态的,不受其他约束,类下面的静态函数,用来制作没有关联的工具包集合
#7 类方法,@classmeithod,只能调用类变量
#8属性方法,@property ,把方法变成静态属性,用户只要调用就可以了,不 需要传参数