1

I have noticed that static or object attributes in python can also be defined outside the class definition

class Test: 
     static_attr=201
     def __init__(self):
         self.object_attr=20

is the class definition and then we do:

t1=Test() 
t2=Test()
t1.new_attr=200000

now after this

print(t1.new_attr) 

prints 200000

print(t2.new_attr) 

throws an error. To me this is a very counter-intuitive OOP concept, as it defeats the purpose of a class, because now each object can have a different set of attributes, even though those attributes are mapped out in .__dict__. Is this bad coding practise in python?

Shashwat
  • 439
  • 7
  • 13
  • 1
    Why would that be defeating the purpose of a class? You *want* to keep state on the instance, so that's where you put your attributes. That's what `self.object_attr = 20` does, assign an attribute on the instance. `self` is just another reference to the instance, just like `t1` and `t2` are. – Martijn Pieters Jun 16 '18 at 18:03
  • 2
    Python is highly dynamic and doesn't restrict access. There is no *privacy model*, so you can add or remove attributes from anywhere. You are trusted to know when it is a good idea to add attributes from code not part of the class. Plenty of great code does so. It is not a bad coding practice. – Martijn Pieters Jun 16 '18 at 18:04

0 Answers0