1
Vývoj / Re:Python - složení objektu za běhu
« kdy: 27. 02. 2024, 13:10:09 »Kód: [Vybrat]
x = [1, 2, 3]
def func1(_):
print('func1')
def func2(_):
print('func2')
def init(self):
self.a = 10
self.b = 20
print('init object')
class_ = type('MyClass', (object,), {'__init__': init, 'x': x, 'func1': func1, 'func2': func2})
instance = class_()
print(instance.__dict__)
print(instance.x)
print(instance.a)
print(instance.b)
instance.func1()
instance.func2()
Týmto spôsobom je možné dynamicky vytvoriť triedy z funkcií, atribútov atď.