vasili111
vasili111

Reputation: 6930

OOP. Passing arguments correctly

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

Answers (3)

Alchimie
Alchimie

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

Igor Rivin
Igor Rivin

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

Ben G.
Ben G.

Reputation: 156

class Thing: #Note: Not Thing(a)
    def __init__(self, a):
        self.foo = a + 2

Upvotes: 2

Related Questions