I have below code:
class Employee:
orgName = 'Credit Cards' # class variable
def __init__(self, name):
self.name = name # instance variable
Sam = Employee('Sam')
print(Sam.orgName) # 'Credit Cards'
Sam.orgName = 'Loans'
print(Sam.orgName) # 'Loans'
print(Employee.orgName) # 'Credit Cards'
So in the above example I understand that when I assign something to Sam.orgName. Python is actually creating an instance variable called 'orgName' and thus the class variable 'orgName' remains unchanged.
But then I tried below code here is where I am confused:
class Employee:
orgName = 'Credit Cards' # class variable
hobbies = ['Hiking']
def __init__(self, name):
self.name = name # instance variable
Sam = Employee('Sam')
print(Sam.hobbies) # 'Hiking'
Sam.hobbies.append('Reading')
print(Sam.hobbies) # 'Hiking', 'Reading'
print(Employee.hobbies) # 'Hiking', 'Reading'
How is it that I am able to modify the class variable here when it should follow the behavior of the first code snippet where Sam.hobbies should have created a list instance variable?
CodePudding user response:
There is a difference between how you modified the string member vs the list member. Initially the Employee
static member is shared by the instance Sam
(when Sam
is initiated, it references whatever Employee
references).
In the list case, you modified this list in-place, which altered the list for both because they point to the same object. In the string case, you changed the assignment of the variable for the Sam
, so that this instance's version of orgName
no longer points to the same thing as the Employee
class does. Note that strings are immutable in python, so you could not have done an in-place modification in the same way anyway.