Dynamically defining instance fields in Python classes

后端 未结 3 1470
闹比i
闹比i 2021-02-05 10:48

I am new to Python having come from mainly Java programming.

I am currently pondering over how classes in Python are instantiated.

I understand that __ini

3条回答
  •  无人及你
    2021-02-05 11:14

    Attributes of Python objects are generally stored in a dictionary, just like the ones you create with {}. Since you can add new items to a dictionary at any time, you can add attributes to an object at any time. And since any type of object can be stored in a dictionary without previous declaration of type, any type of object can be stored as an attribute of an object.

    In short, my_object.abc = 42 is (often) just a shorthand for my_object.__dict__["abc"] = 42.

    It is possible to define objects without a __dict__ by defining the __slots__ attribute, or to override certain special methods and store attributes in some other way, though most of the time you shouldn't do that.

提交回复
热议问题