masterofnothing
masterofnothing

Reputation: 55

Why is it not illegal in Python to be able to add attributes after a class is already defined?

For example:

class Car:
  pass
jeep = Car()
jeep.color = 'blue'

This is perfectly legal and runs fine. I understand that python is pretty dynamic but doesn't this violate some principle of oop?

Upvotes: 1

Views: 156

Answers (1)

OnesimusUnbound
OnesimusUnbound

Reputation: 2946

http://docs.python.org/tutorial/classes.html#odds-and-ends

To dynamically set up the fields and value when they can only be known at run time.

Python does not prevent you from dynamically creating instance properties, though you can decide not to do so if you have no very good reason to do so. Python is quite a powerful language, though care must be excercise to avoid abusing this sort of power to do crazy things with it's flexibility.

Upvotes: 2

Related Questions