Improper use of a reserved word

So, I have some kind of god left by the old code that uses the reserved word property, um wrong. In the base class that is inherited, they are mostly implemented.

class TestClass(object):

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

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


test = TestClass('test property')
print(test.property)

The work is done without errors. If you add another method below that you get,

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)

What throws away:

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

TypeError: 'property' object is not callable

Since you know that in the local namespace you have rewritten 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)

You can get around this if you always define your rewriting propertyat the bottom of your class. If the method is propertydefined only in the base class, you inherit from what works, too, because namespaces.

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)

, , GAAAAH, property , ?

+4
3

dont shadow builtins... ,

__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

, , , @property python. , , , . ... ,

+4

, property, . . , , property , ...

BTW, property arg __init__ property, , .

, - , , .

, , property @property . , , . , Python, , Python...

+3

property . , , , , .

tproperty = property

class Test(...)

    @tproperty
    def property(self):
        ....
0

All Articles