-
静态方法
通过@staticmethod来定义,静态方法在类中,但在静态方法里访问不了类和实例中的属性,但静态方法需要类来调用
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" class Person(object): def __init__(self,name): self.name = name @staticmethod def eat(self,food): print("%s is eating %s"%(self.name,food)) if __name__ == ‘__main__‘: p = Person(‘John‘) p.eat(‘meat‘)
运行,报错
把eat方法的参数去掉,直接打印,可以直接调用
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" class Person(object): def __init__(self,name): self.name = name @staticmethod def eat(): print("John is eating") if __name__ == ‘__main__‘: p = Person(‘John‘) p.eat()
运行结果
如果要给eat()传参数的话,可以把实例化的Person传入
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" class Person(object): def __init__(self,name): self.name = name @staticmethod def eat(self): print("%s is eating"%self.name) if __name__ == ‘__main__‘: p = Person(‘John‘) p.eat(p)
运行结果
-
类方法
类方法通过@classmethod来定义
类方法只能访问类变量,不能访问实例变量
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" class Person(object): name = ‘Jack‘ def __init__(self,name): self.name = name @classmethod def eat(self): print("%s is eating"%self.name) if __name__ == ‘__main__‘: p = Person(‘John‘) p.eat()
运行结果
传入了实例变量John,但打印的却是Jack
因为类方法不能访问实例变量,所以类方法访问了类里的类变量
-
属性方法
通过@property来定义属性方法
把类中的方法变为静态属性
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" class Person(object): def __init__(self,name): self.name = name @property def eat(self): print("%s is eating"%self.name) if __name__ == ‘__main__‘: p = Person(‘John‘) p.eat
按照调用属性的方法来调用属性方法
如果想给属性方法传参数的话,要使用setter