繁体   English   中英

Python中的每类@property装饰器

[英]Per-class @property decorator in Python

Python为这样的实例支持@property装饰器:

class MyClass(object):
    def __init__(self):
        self._friend_stack = [1]
    @property
    def current_friend(self):
        return self._friend_stack[0]

myobj = MyClass()
myobj.current_friend # 1

是否有可能为类具有类似的东西,以便行为是这样的(例如,与setter和getter方法一起):

class MyClass(object):
    _friend_stack = [1]

    @property
    def current_friend(cls):
        return cls._friend_stack[0]

MyClass.current_friend # 1

在Python 3中:

class MyMeta(type):
    def current_friend(cls):
        return cls._friend_stack[0]
    current_friend = property(current_friend)

class MyClass(metaclass=MyMeta):
    _friend_stack = [1]

[疯狂的笑声跟着]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM