为什么我可以访问 list 类型的类变量并更改其内容但不能访问 string 类型?
python 193
原文标题 :Why am I able to access the class variable of type list and change its contents but not of type string?
我有以下代码:
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'
所以在上面的例子中,我明白当我给 Sam.orgName 赋值时。Python 实际上是在创建一个名为 ‘orgName’ 的实例变量,因此类变量 ‘orgName’ 保持不变。
但是后来我尝试了下面的代码,这是我感到困惑的地方:
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'
当它应该遵循 Sam.hobbies 应该创建列表实例变量的第一个代码片段的行为时,我如何能够在此处修改类变量?