python@classmethod,@staticmethod ,def 静态方法,类方法,普通方法

版权声明:QQ群:796245415 个人技术交流,禁止用作商业活动 https://blog.csdn.net/chen498858336/article/details/83795406

# coding = utf-8
class Test(object):
    def __init__(self, name):
        self.age = 33
        self.name = name
        
    #  普通方法,只能被对象调用
    def walk(self, place):
        print place, self.walk.__name__, self
        
    #静态方法既可以被对象也可以被类名称调用
    @staticmethod
    def play(string):
        print string
        
     #可以被对象也可以被类名称
    @classmethod
    def eat(cls, food):
        print food, cls, cls.walk.__name__
if __name__ == "__main__":
    Test('Jack').walk('shenzhen')  #普通方法仅仅可以被对象调用其实我两步合在一起了
    Test('Jack').play('water')   #静态方法 被对象调
    Test.play('fire')   # 静态方法被类名称调
    Test('jack').eat('apple')  # 类方法被对象调
    Test.eat('tomato')   # 类方法被类名称调

猜你喜欢

转载自blog.csdn.net/chen498858336/article/details/83795406