Reputation: 2863
Possibly a dumb question, but I'm more used to Java and the likes and thus don't get why I can do this:
class A:
def __init__( self ):
pass
a = A()
a.description = "whyyy"
print a.description
And have it print out whyyy
instead of giving me an error.
Upvotes: 0
Views: 56
Reputation: 526723
Because Python objects are dynamic - they aren't required to follow a rigid schema.
Creating an instance of a class gives you an object that already has certain things defined, but you're allowed to dynamically add other things to that instance; you're not restricted to the original class definition.
Upvotes: 2
Reputation: 6814
Variables spring into existence by being assigned a value, and they are automatically destroyed when they go out of scope.
For objects, you can add new fields dynamically on runtime. Note that this won't change the class description. Only the current instance.
class A:
def __init__( self ):
pass
a = A()
a.description = "whyyy"
print a.description
b = A()
print b.description # Should return an error
Upvotes: 0