0
class Test(object):
    def __init__(self):
        self.name = "changzhi"

    @property
    def __name__(self):
        return self.name

>>> a = Test()
>>> a.__name__
>>> "changzhi"
>>> a.name
>>> "changzhi"
>>> a.__name__() 
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: 'str' object is not callable

Here are my thoughts:

  1. When I run a.__name__, it returns "changzhi" because __name__ is a property of class Test(object) which is modified by "@property".
  2. When I run a.name, it returns "changzhi" because name is a class property which is defined by __init__.
  3. When I run a.__name__(), it occurs an error because __name__ is a class property ,not a class function Do all of my thoughts right ? Could someone explains to me ? And what the differences between __name__ and self.name(in __init__) ? Thanks a lot!
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
changzhi
  • 2,641
  • 9
  • 36
  • 46

1 Answers1

3

Decorating a function with self.property is just a fancy way of making a property. You can also do it manually like this:

>>> class X:
    def __init__(self):
        self.name = "Me"
    def set_name(self, other):
        self.name = other
    def get_name(self):
        return self.name + "ABCDE"
    dynamicName = property(get_name, set_name)


>>> inst = X()
>>> inst.dynamicName
'MeABCDE'
>>> inst.dynamicName = "You"
>>> inst.dynamicName
'YouABCDE'

Note that dynamicName is a property, not a function. Well, it's just a syntatic sugar. Now, let's move on to your question. We can do this by using the @property decorator:

>>> class Y:
    def __init__(self):
        self.name = "Me"
    @property
    def dynamicName(self):
        #This would be the getter function
        return self.name + "ABCDE"
    @dynamicName.setter
    def set_name(self):
        self.name = other


>>> inst = Y()
>>> inst.dynamicName
'MeABCDE'

In the snippet above, dynamicName is decorated by the property function. But, result of this decoration is not a function, but an attribute! This leads to your confusion.

You can simply test it:

>>> type(inst.dynamicName)
<class 'str'>

Hope this helps!

aIKid
  • 26,968
  • 4
  • 39
  • 65
  • The type of `inst.dynamicName` is `` because it is modified by `@property`. Does it right? – changzhi Jan 17 '14 at 07:05
  • You can learn more about decorators [in this question](http://stackoverflow.com/a/1594484/2106009). Actually, when you decorate a function `a` with `@b`, you're just calling `b(a)`. The returned attribute depends on the `b` function. – aIKid Jan 17 '14 at 07:08