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!

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

The type of inst.dynamicName is <class 'str'> because it is modified by @property. Does it right?
You can learn more about decorators in this question. Actually, when you decorate a function a with @b, you're just calling b(a). The returned attribute depends on the b function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.