-2

Pyhon allows to create any class instance attribute just like new variable and you don't need to define them in class definition. What's the purpose of that?

class MyClass:
    def __init__(self):
        pass

obj = MyClass()
obj.a = '1';
print(obj.a)
#>> 1

P.S. found interesting example of such kind of usage Can you use a string to instantiate a class There dynamically created attributes used to store dynamically instatiated classes

  • 1
    There is no "purpose" to this. There is simply no functional difference between accessing an instance "inside" and "outside" of a class definition. Have you *tested* whether "This new attributes isn't visible for class methods"? – MisterMiyagi Aug 17 '20 at 18:02
  • 1
    Actually, it's your choice to shoot in own leg or not. – Olvin Roght Aug 17 '20 at 18:03
  • 2
    You seem to have missed working through a tutorial on classes and instances. I suggest you do that, and then rewrite your question. – Prune Aug 17 '20 at 18:03
  • Python is a [Dynamic programming language](https://en.wikipedia.org/wiki/Dynamic_programming_language), so this is the expected behaviour. And you are simply wrong that such attributes aren't visible inside the methods of the class. – ekhumoro Aug 17 '20 at 18:21

1 Answers1

0

The purpose of this is simplicity: There is no difference to accessing an instance inside or outside of a method. The object seen inside and outside of a method is completely equivalent, and by extension the same rules apply anywhere:

class MyClass:
    def __init__(self):
        print(self)  # <__main__.MyClass object at 0x119636490>
        self.b = 12  # assign to an instance

obj = MyClass()
print(obj)           # <__main__.MyClass object at 0x119636490>
obj.b = 12           # # assign to an instance

Note that one can read and write attributes inside and outside methods, and these attributes are visible inside and outside of methods. In fact, Python has no concept of "inside" and "outside" of methods, aside from a few code-rewrites such as double-underscore name mangling.

This is both a result and the enabling feature to allow various inbuilt features of other languages to work without explicit support. For example, Python allows the equivalent of extension methods without extra syntax/functionality:

class MyPoint:
    def __init__(self, x, y):
        self.x, self.y = x, y

# Oops, forgot a repr!
def my_point_repr(self):
    return f'{self.__class__.__name__}(x={self.x}, y={self.y})'

MyPoint.__repr__ = my_point_repr
print(MyPoint(1, 2))  # MyPoint(x=1, y=2)
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119