I am trying to call the method of the class having no arguments but it is failing.
class ab:
def a():
print("in a")
def b():
print("in b")
if __name__ == '__main__':
b()
ab.a()
Error:
in b
Traceback (most recent call last):
File "p.py", line 11, in <module>
ab.a()
TypeError: unbound method a() must be called with ab instance as first argument (got nothing instead)
I have also tried to modify the code as below but not successful
class ab:
def a():
print("in a")
def b():
print("in b")
if __name__ == '__main__':
b()
c=ab()
c.a()
Error:
in b
Traceback (most recent call last):
File "p.py", line 12, in <module>
c.a()
TypeError: a() takes no arguments (1 given)
# Could be wrong but
if __name__ == "__main__"
# is looking for the def main
Methods need to be declared with
self
as the first parameter, e.g.
class Foo:
def bar(self):
pass
f = Foo()
f.bar()
Alternatively you can define it as a static method:
>>> class Foo(object):
... @staticmethod
... def bar():
... print('bar')
...
>>> f = Foo()
>>> f.bar()
bar
Two issues. As above, need self in the function definition. Next, you need an ab object in order to call the function. The class is just a template. So, in the example below, we create the cab object of type ab, then call the function:
class ab:
def a(self):
print("in a")
def b():
print("in b")
if __name__ == '__main__':
b()
cab = ab()
cab.a()
Output:
in b
in a
(Oct-30-2019, 06:24 PM)ndc85430 Wrote: [ -> ]Methods need to be declared with self
as the first parameter, e.g. class Foo: def bar(self): pass f = Foo() f.bar()
Yes, with self as argument it is working. That being said, Is it necessary to have all the class methods should have at least 1 argument (self) in our case. Can't we have no arguments ?
(Oct-31-2019, 12:03 PM)dataplumber Wrote: [ -> ]Is it necessary to have all the class methods should have at least 1 argument (self) in our case
all instance and class methods should have one argument. For instance methods, by convention, we call that argument
self
. For class methods we use, again by convention,
cls
.
And there are staticmethods that answer to your next question:
(Oct-31-2019, 12:03 PM)dataplumber Wrote: [ -> ]Can't we have no arguments ?
As ichabood explained you need to declare it staticmethod. However in this case the question is does it really belong to a class or can simply be a function, outside class. i.e. if it doesn't need to access instance or the class
Google the difference between instance, class, static methods and simple function
(Oct-31-2019, 12:03 PM)dataplumber Wrote: [ -> ] (Oct-30-2019, 06:24 PM)ndc85430 Wrote: [ -> ]Methods need to be declared with self
as the first parameter, e.g. class Foo: def bar(self): pass f = Foo() f.bar()
Yes, with self as argument it is working. That being said, Is it necessary to have all the class methods should have at least 1 argument (self) in our case. Can't we have no arguments ?
Thank you. That Answers my question.