基本
class Humen(object):
color = 'white,black,yellow' #静态字段,属于类
def __init__(self,name,age,where,love='None',secret='None'): #动态方法,属于对象
#构造函数
self.name = name #动态字段,属于对象
self.age = age
self.where = where
self.love = love
self.__secret = secret #私有字段,外部无法直接访问
@staticmethod #静态方法,属于类,外部跟方法一样
def marry():
print('a big part of poeple will be married')
@property #特性,属于类
def character(self):
print('people are happiness')
def show_secret(self): #通过方法间接访问私有字段
print ('his secrct is {}'.format(self.__secret))
def badhabit(self): #动态方法,有传入self参数
print('Drinking, Eatting Much, Greedy')
def __secrect2(self): #私有方法,前面加上__
print('私有方法')
def show_secret2(self): #通过方法访问间接私有方法
self.__secrect2()
@property #只读 #通过特性访问私有字段
def secrect_attr(self):
return self.__secret
@secrect_attr.setter #只写,可从外部改,有object用这个
def secrect_attr(self,value):
self.__secret = value
def __del__(self): #类对象生存的最后一刻
#析构函数
print('解释器要销毁我了,我要做最后一次呐喊')
def __call__(self): #call方法,调用为instance()
print('I am called method')
P1 = Humen('Guoql',19,'Fujian','Runing','love some')
print('{},{},{},{}'.format(P1.name,P1.age,P1.where,P1.love))
P2 = Humen('LiYang',23,'beijing')
print('{},{},{},{}'.format(P2.name,P2.age,P2.where,P2.love))
a = Humen.color #访问静态字段
print('{}'.format(a))
b = Humen.marry() #访问静态方法
print('{}'.format(b)) #为什么返回了一个None
c = Humen.character #访问特性1
print('{}'.format(c))
d = P1.character #访问特性2
print('{}'.format(d))
P1.show_secret2()
print('通过特性访问私有字段{}'.format(P1.secrect_attr))
e = P1._Humen__secrect2() #外部强制访问私有方法,不建议
P1.secrect_attr = 'his secrect has changed from outdoor'
print('{}'.format(P1.secrect_attr))
P3 = Humen('XiaoMing',23,'beijing') #创建类的实例
P3.show_secret2() #使用类的方法
P3() #使用__call__
class Women(Humen): #继承Humen父类
def __init__(self,name,beautiful=True,marry=False):
self.name = name
self.beautiful = beautiful
self.marry = marry
def badhabit(self):
print('Shoppng and Eating') #重写继承的badhabit方法
print('{}'.format(Humen.badhabit(self))) #父类原本的badhabit方法
def foo(self): #调用父类init构造方法Humen.__init__(self)
a = Humen.__init__(self) #1 Humen.__init__(self)
print('{}'.format(a)) #2 super(Women,self).__init__()
P3 = Women('Xuesui','Nice')
print("{},{},doesn't married".format(P3.name,P3.beautiful))
P3.badhabit() #为什么又返回了一个None