Reputation: 307
My code
class MyClass:
i =123
def f2(a):
global b
print (a)
print (b)
b = 9
x = MyClass()
x.f2(1)
It does not work as expected
TypeError: f2() takes 1 positional argument but 2 were given
Why? How to inspect function and positional arguments? If I change
x.f2()
<__main__.MyClass object at 0x7fb3f028fbe0>
9
In this case I can not pass a.
Upvotes: 0
Views: 933
Reputation: 130
One of the 'OOP' reasons to create functions inside a class are inheriting constructors.
You've created the class 'MyClass' and the function f2() is one of the functions inside it.
To convey that the function belongs to/ is a part of the class, you have to pass a default parameter 'self' in the function or it is not recognized by the interpreter.
Coming to your error: You are passing 1 to the function, but by default there is a 'self' passed to all the class functions. Two solutions possible,
Either make the function static by the decorator
@static
def f2(a):
pass
*this conveys that the function is just inside the class but doesn't belong to it. It just is there.
pass a 'self' in the function.
def f2(self, a):
pass
Hope it helps.
Upvotes: 2
Reputation: 381
class MyClass:
i =123
def f2(self,a):
global b
print (a)
print (b)
b = 9
write as this ,you will work ok
Upvotes: 2
Reputation: 3419
class MyClass:
i =123
def f2(self,a):
print (a)
x = MyClass()
x.f2(1)
OUTPUT
1
Upvotes: 2