Reputation: 6930
This works:
class Thing():
def __init__(self):
a=2
exec(f'self.foo ={a} + 2')
x = Thing()
print(x.foo)
This does not works works:
a=2
class Thing(a):
def __init__(self, a):
exec(f'self.foo ={a} + 2')
x = Thing(a)
print(x.foo)
Question: How to make second example to work properly (it should put 2
inside x
)?
Upvotes: 0
Views: 43
Reputation: 426
You don't need to use 'a' as argument when you defined it out of class:
a=2
class Thing:
def __init__(self):
exec(f'self.foo ={a} + 2')
x = Thing()
print(x.foo)
Upvotes: 1
Reputation: 4864
Replace class Thing(a)
with class Thing()
and you are good. The argument to the class name is the class you are inheriting from, not the argument to instatiation.
Upvotes: 2
Reputation: 156
class Thing: #Note: Not Thing(a)
def __init__(self, a):
self.foo = a + 2
Upvotes: 2