[英]In python can two different objects of same class have different no of variables
class car:
pass
firstcar = car()
secondcar = car()
firstcar.wheels = 4
print(firstcar.wheels)
output: 4
output:4
But when I try print(type(secondcar.wheels))
it gives me AttributeError但是当我尝试
print(type(secondcar.wheels))
它给了我AttributeError
You're adding an attribute of wheels
to the instance firstcar
not to the car
class .您将
wheels
属性添加到实例firstcar
而不是car
class 。
Each instance has a __dict__
attribute, which holds all other attributes, and effectively all you're doing with每个实例都有一个
__dict__
属性,该属性包含所有其他属性,并且实际上是您正在使用的所有属性
firstcar.wheels=4
is是
firstcar .__dict__[wheels]=4
#nb. this won't actually work as you cant assign to object __dict__s this way;
#it's just an analogy!
This might be clearer now why this doesn't affect secondcar现在可能更清楚为什么这不会影响第二辆车
firstcar = car()
secondcar = car()
firstcar.wheels=4
print(firstcar.__dict__) #{'wheels': 4}
print(secondcar.__dict__)#{}
In contrast you can actually add variables to classes in this way:相反,您实际上可以通过这种方式将变量添加到类中:
class car:
pass
car.wheels=""
firstcar = car()
secondcar = car()
firstcar.wheels = 4
print(firstcar.wheels)
print(secondcar.wheels)
Which will not give you an attribute error.这不会给你一个属性错误。 In fact you can add attributes to the class after you create your instances and still avoid the error.
事实上,您可以在创建实例后将属性添加到 class 并仍然避免错误。
(This is just for explanation, not suggesting to use it in real life, it could lead to some very confusing code!) (这只是为了解释,不建议在现实生活中使用它,它可能会导致一些非常混乱的代码!)
Yes, Two objects of the same class can have different no.是的,同一个 class 的两个对象可以有不同的编号。 of instance variables, But they always have the same no.
实例变量,但它们始终具有相同的编号。 of class variables.
class 变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.