静态方法、类方法、属性方法

静态方法:通过加@staticmethod实现,只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性。

class Person(object):
    @staticmethod
    def person_speak(obj):
        print('I like Hiphop!')

me = Person()
me.person_speak(me)
Person.person_speak(me)

# I like Hiphop! 
# I like Hiphop! 

类方法:通过加@classmethod实现,只能访问类变量,不能访问实例变量。

class Person(object):
    sex = 'man'
    def __init__(self, sex):
        self.sex = sex
    # @classmethod
    def hello(self):
        print('I am {}'.format(self.sex))

me = Person('woman')
me.hello()

# I am woman
# 去掉装饰器的注释后,输出
# I am man

属性方法:通过加@property实现

猜你喜欢

转载自www.cnblogs.com/allenzhang-920/p/9393357.html