1.静态方法:只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性。相当于类的工具包。
class Dog(object): def __init__(self,name): self.name=name @staticmethod #实际上跟类没什么关系了,相当于一个独立的函数。 def eat(self,food): print("%s is eating %s"%(self.name,food)) def drink(self,food): print("%s is drinking %s"%(self.name,food)) d1=Dog("Lily") d1.drink("Cooola") #drink正常执行 d1.eat("baozi") #静态方法
运行结果:
Traceback (most recent call last): File "<encoding error>", line 13, in <module> TypeError: eat() missing 1 required positional argument: ‘food‘ Lily is drinking Cooola
2.类方法只能访问类变量,不能访问实例变量。
class Dog(object): n=123 def __init__(self,name): self.name=name @classmethod #类方法,被修饰的下列函数只能访问类变量,不能访问实例变量。 def eat(self,food): print("类变量%s" % self.n) print("%s is eating %s"%(self.name,food)) def drink(self,food): print("%s is drinking %s"%(self.name,food)) d1=Dog("Lily") d1.drink("Cooola") #drink正常执行 d1.eat("baozi") #类方法
运行结果:
Lily is drinking Cooola 类变量123 Traceback (most recent call last): File "<encoding error>", line 15, in <module> File "<encoding error>", line 8, in eat AttributeError: type object ‘Dog‘ has no attribute ‘name‘
3.属性方法
把一个方法变成一个静态属性。隐藏实现细节。就不能加()调用了。给属性方法赋值
class Dog(object): 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 d=Dog("Lily") d.eat d.eat="baozi" #属性方法 d.eat
运行结果:
Lily is eating None set to food: baozi Lily is eating baozi
4.属性方法在实例中不能以del d.eat 的方式删除。删除方法如下:
class Dog(object): 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("Lily") d.eat d.eat="baozi" #属性方法 d.eat del d.eat d.eat
运行结果:
Lily is eating None set to food: baozi Lily is eating baozi 删除完毕 Traceback (most recent call last): File "<encoding error>", line 26, in <module> File "<encoding error>", line 9, in eat AttributeError: ‘Dog‘ object has no attribute ‘_Dog__food‘
时间: 2024-10-20 20:13:53