【发布时间】:2021-10-19 11:00:57
【问题描述】:
我找到了原因。 Python变量,list, dict, set是可变对象,str, tuple string int float bool是不可变对象,所以当class属性的list、dict、set被修改时,不会生成对应的。实例属性的实例属性只有在实例属性的list、dict、set被重新赋值时才会生成。给实例属性str和tuple string int float bool赋值会将类属性中的属性名复制到实例属性中,然后重新赋值。
如果我想让类属性和实例属性的列表不同,可以同时初始化类属性和实例属性:
class MyClass:
property = []
def __init__(self):
self.property = []
pass
def add(self, value):
self.property.add(value)
a = MyClass()
print(id(a.property))
print(id(a.__class__.property))
2352192165696
2352189676480
以下是我原来的问题:
我有一个带有属性的类和一个带有空值的列表。当生成了a和b的两个实例并向属性添加元素时,发现属性没有实例化。使用 id 查看 a.property 和 b.property。内存地址是一样的。为什么?
property attribute 如何变成instance attribute?
我的代码示例如下:
class MyClass:
property = []
def __init__(self):
pass
def append(self, value):
self.property.append(value)
a = MyClass()
b = MyClass()
a.append(1)
print(a.property)
b.append(1)
print(a.property)
print(b.property)
print(id(a.property))
print(id(b.property))
结果是:
[1]
[1, 1]
[1, 1]
1866383694784
1866383694784
我尊重的结果:
[1]
[1]
[1]
【问题讨论】:
-
用你自己的话说,当你写
def __init__(self):时,你认为这是为了什么?另外,你自己对research这个问题做了什么尝试?例如,您是否尝试输入python instance attributeinto a search engine? Stack Overflow 不是教程中心。 -
你不需要类方法来改变类变量的值
-
不要编辑你的问题来提出一个全新的问题。但同样,您可以通过在这里进行预期的研究来轻松回答这个问题。
-
@KarlKnechtel 我也知道可以在
def __init__(self)中定义。我的类属性和实例属性有不同的用途,def __init__(self)中省略了其他赋值。来starkoverflow是带着问题来提问的。感觉我问的不是新问题,而是对我之前的问题的一个不准确的描述。 -
@KarlKnechtel 这样我先把问题改回原来的状态,然后再问。