Not using the __init__ constructor?
That is, is there a declaration option (variable initialization) that will be instance fields without using a constructor?
Not using the __init__ constructor?
That is, is there a declaration option (variable initialization) that will be instance fields without using a constructor?
class A: b = 1 def c(self, z): print(self) return z a = A() print(ab) Ac = c print(ac(2)) ad = c print(ad(a, 3)) ae = 4 print(ae) class D(dict): pass d = D(name='my_name', num=3) print(d) There are several options. In all the examples below, I will show how to assign a field "x" equal to 1 to a class object.
First: Declare a "bare" instance of the class, and with the ready-made instance, use your hands to set the necessary attributes.
class A: pass a = A() ax = 1 Second: Use the new special method.
class A: def __new__(cls): obj = super(A, cls).__new__(cls) obj.x = 1 return obj Third: write the initialization method, and run it either by hand after creating the instance, or automatically from new.
class A: def my_init(self): self.x = 1 a = A() a.my_init() This is just what offhand comes to mind. I suspect, then you can come up with similar options.
But the correct way is to use init.
Source: https://ru.stackoverflow.com/questions/613030/
All Articles