简体   繁体   中英

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

But when I try print(type(secondcar.wheels)) it gives me AttributeError

  1. When I create c1.wheels then why wheels is not created as an instance variable for object c2.
  2. If wheels is not created for c2 then is it that object of same class can have different number of instance variables in python.

You're adding an attribute of wheels to the instance firstcar not to the car class .

Each instance has a __dict__ attribute, which holds all other attributes, and effectively all you're doing with

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.

(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. of instance variables, But they always have the same no. of class variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM