There are two codes as below:
class State:
country = "China"
def __init__(self):
print(State.country)
obj = State()
and:
class State:
country = "China"
def __init__(self):
print(self.country)
obj = State()
They both work well and have output:
China
But what's different between these two ways?
Thank you
This article provides details about what's happening here, and how you should handle it.
https://www.toptal.com/python/python-class-attributes-an-overly-thorough-guide
In both cases, the code is accessing the class attribute State.country
. Since each instance of State
has access to the class attribue, self.country
will return the same value as State.country
--unless you modify it.
If you choose to assign a new value to an instance of State
, it will not update "the instance's country attribute" because the instance has no country attribute. Instead, it will create an instance attribute called country for that particular instance, and in the future, when you make a call to the instance's country attribute (e.g. self.country
), the Python interpreter will find the instance attribute first, but the class attribute is still there; the interpreter will simply never find it as long as the instance attribute with the same name still exists.
The following demonstrates this:
class State:
country = "China"
def __init__(self):
pass # The constructor is unnecessary for this example
s = State()
print(s.country) # Prints "China"
print(State.country) # Prints "China"
s.country = "Japan" # State.country still equals "China", but s.country has been
# created and initialized to "Japan"
print(s.country) # Prints "Japan"
print(State.country) # Prints "China"
new_s = State()
print(new_s.country) # Prints "China"
del s.country # Deletes the instance attribute country created for s
print(s.country) # Prints "China"; now that the instance attribute has been
# deleted, the Python interpreter will fail to find s.country
# within the instance namespace, and so it will search the
# class namespace and it will find the class attribute State.country
This all goes to show that you should research the Python conventions for keeping class attribute and instance attributes distinct, and using each only in the appropriate scenarios.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With