静态字段在内存中只保存一份
普通字段在每个对象中都要保存一份
class Company:
place='America' #静态字段
def __init__(self,name):
self.name=name #普通字段
obj=Company('Google')
print(obj.name) #直接访问普通字段
print(Company.place) #直接访问静态字段
#Output:
#Google
#America
普通方法:由对象调用;至少一个self参数;执行普通方法时,自动将调用该方法的对象赋值给self
类方法:由类调用;至少一个cls参数;执行类方法时,自动将调用该方法的类复制给cls
静态方法:由类调用;无默认参数
class testfun:
def __init__(self,tool):
self.tool=tool
def ordinary_fun(self): #定义普通方法
print('ordinary method')
@classmethod
def class_fun(cls): #定义类方法
print('class method')
@staticmethod
def static_fun(): #定义静态方法
print('static method')
tt=testfun('bike')
tt.ordinary_fun() #调用普通方法
testfun.class_fun() #调用类方法
testfun.static_fun() #调用静态方法
#Output:
#ordinary method
#class method
#static method
Python中的属性其实是普通方法的变种
class profun():
def fun(self): #定义普通方法
print('test ordinary fun OK!')
@property
def prop(self): #定义属性
print('test prop OK!')
testobj=profun()
testobj.fun() #调用普通方法
testobj.prop #调用属性
#Output:
#test ordinary fun OK!
#test prop OK!
定义属性时,在普通方法的基础上添加 @property 装饰器,仅有一个self参数;
调用属性时,无需括号
class book():
def __init__(self,chapter_now,page_read):
self.chapter_now=chapter_now #当前读到章节
self.page_read=page_read
self.each_chapter=100 #每张默认100页
@property
def endpage(self):
num=(self.chapter_now-1)*self.each_chapter+self.page_read
return num
obj=book(2,35)
obj.endpage
#Output:
#135