滥用"财产"保留字

Tri*_*ews 5 python properties decorator python-2.7

所以我有一些上帝遗弃的遗留代码使用保留字property,这是错误的.在继承的基类中,它们已基本实现.

class TestClass(object):

    def __init__(self, property):
        self._property = property

    @property
    def property(self):
        return self._property


test = TestClass('test property')
print(test.property)
Run Code Online (Sandbox Code Playgroud)

哪个运行没有错误.如果您在下面添加另一种方法,

class TestClass2(object):

    def __init__(self, property):
        self._property = property

    @property
    def property(self):
        return self._property

    @property
    def other_property(self):
        return 'test other property'


test = TestClass2('test property')
print(test.property)
print(test.other_property)
Run Code Online (Sandbox Code Playgroud)

哪个投掷:

---> 10     @property
     11     def other_property(self):
     12         print('test other property')

TypeError: 'property' object is not callable
Run Code Online (Sandbox Code Playgroud)

因为您知道您已property在本地命名空间中覆盖.

class TestClass3(object):

    def __init__(self, property):
        self._property = property

    @property
    def other_property(self):
        return 'test other property'

    @property
    def property(self):
        return self._property


test = TestClass3('test property')
print(test.property)
print(test.other_property)
Run Code Online (Sandbox Code Playgroud)

如果您始终property在课程底部定义覆盖,则可以解决此问题.如果property方法仅在基类上定义,那么从事物中继承的方法也可以解决,因为名称空间.

class TestClass4(TestClass):

    def __init__(self, property):
        super(TestClass4, self).__init__(property)

    @property
    def other_property(self):
        return 'test other property'


test = TestClass4('test property')
print(test.property)
print(test.other_property)
Run Code Online (Sandbox Code Playgroud)

我正义的愤慨说我们必须在大量遗留代码中更新这个变量名,因为GAAAAH,但除了必须记住property在很少修改的基类中添加定义定义之上的新方法之外,这实际上并没有破坏什么事对吗?

Jor*_*ley 4

不要隐藏内置函数...几乎不需要重构,您就可以完全避免隐藏内置函数

使用__getattr__而不是@property返回您的_property会员...

class TestClass(object):
    def __init__(self):
        self._property = 12

    def __getattr__(self,item):
        if item == "property": 
           #do your original getter code for `property` here ... 
           # now you have not overwritten the property keyword at all
           return getattr(self,"_property") # just return the variable
class TestClass2(TestClass):
    def __init__(self):
        self._property = 67

print TestClass2().property

class MySubClass(TestClass):
    @property
    def a_property(self):
        return 5

print MySubClass().property
print MySubClass().a_property
Run Code Online (Sandbox Code Playgroud)

@property真的,顺便说一句,恕我直言,没有任何充分的理由在 python 中使用。它所做的只是最终让其他程序员感到困惑,并掩盖了您实际上正在调用函数的事实。我曾经经常这样做......我现在避免这样做,除非我有一个非常非常令人信服的理由不这样做