0

I defined such simple class as below:

>>> class myclass(object):
    name = "google"

And I am creating an instance to call name attribute

>>> a = myclass()
>>> a.name
'google'

and also calling it directly from the class itself.

>>> myclass.name
'google'

So far (as I am having background with C# and Java) I will call myclass.name static invocation and calling static members from instances are fine.

But what I am observing is till I set a.name with another value, changing myclass.name is also affecting a.name. Once I set a.name, changing myclass.name doesn't affect the a.name any more and they begin to have different values.

You can see the whole experiment below:

>>> class myclass(object):
    name = "google"


>>> myclass.name
'google'
>>> a = myclass()
>>> a.name
'google'
>>> myclass.name = "yahoo"
>>> a.name
'yahoo'
>>> myclass.name = "hello world"
>>> a.name
'hello world'
>>> myclass.name
'hello world'
>>> myclass.name = "another trick"
>>> myclass.name
'another trick'
>>> a.name
'another trick'
>>> a.name = "I changed the value of a"
>>> a.name
'I changed the value of a'
>>> myclass.name
'another trick'
>>> myclass.name = "changed again"
>>> a.name
'I changed the value of a'

I would like someone to explain the reason behind this behavior.

Thanks.

1 Answer 1

4

I took a look at Python Data Model documentation. If you skip ahead to "Class instances" section, you will see the crucial explanation:

Attribute assignments and deletions update the instance’s dictionary, never a class’s dictionary.

So in your example, when you do a.name = ..., you introduce a new key name into a's __dict__. After that when you access name attribute, the standard attribute lookup mechanism looks into a's __dict__ first.

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

Comments

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.