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

静态方法:通过加@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实现,把一个方法变成静态属性

class Person(object):
    n = 1
    @property
    def hello(self):
        print(self.n)

me = Person()
me.hello

# 输出
# 1

一般的属性都可以赋值,但是属性方法的赋值特殊处理

class Person(object):
    def __init__(self):
        self.__n = 1
    @property
    def hello(self):
        return self.__n
    @hello.setter
    def hello(self, n):
        self.__n = n


me = Person()
print(me.hello) # 1
me.hello = 666
print(me.hello) # 666

同理,也可以删除

class Person(object):
    def __init__(self):
        self.__n = 1
    @property
    def hello(self):
        return self.__n
    @hello.setter
    def hello(self, n):
        self.__n = n
    @hello.deleter
    def hello(self):
        del self.__n

me = Person()
me.hello = 666
del me.hello
me.hello

Traceback (most recent call last):
  File "oop.py", line 19, in <module>
    me.hello
  File "oop.py", line 8, in hello
    return self.__n
AttributeError: 'Person' object has no attribute '_Person__n'

 

posted @ 2018-07-30 23:02  AllenZhang_(*^▽^*)  阅读(143)  评论(0编辑  收藏  举报