python 静态方法、类方法、属性方法详解

'''
class Dog(object):

def __init__(self,name):
self.name = name

@staticmethod#实际上跟类没有什么关系了。eat和类的关系截断了,只是类下面函数
#静态方法:只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性
def eat(self):
print('%s is eating %s'%(self.name,'dd'))

d = Dog('test')
d.eat(d)


#类方法:只能访问类变量,不能访问实例变量
class Dog(object):
name ='testing'
def __init__(self,name):
self.name = name

@classmethod
def eat(self):
print('%s is eating %s'%(self.name,'dd'))

d = Dog('test')
d.eat()
'''
#属性方法:把一个方法变成一个静态属性

class Dog(object):
name ='testing'
def __init__(self,name):
self.name = name
self.__food = None

@property
def eat(self):
print('%s is eating %s'%(self.name,self.__food))
@eat.setter
def eat(self,food):
print("set to food:",food)
self.__food = food#赋值

@eat.deleter
def eat(self):
del self.__food
print('删除了')
d = Dog('test')
d.eat
d.eat = "包子"
d.eat

del d.eat#无法通过del删除属性
posted @ 2020-07-15 22:08  安好_世界  阅读(216)  评论(0编辑  收藏  举报