Reputation: 141
I'm writing a simple code snippet here, but unable to run the code
class test:
def __init__(self):
pass
def functiona(self, a):
b = a+0
print(b)
def functionb(self):
a = 5
self.functiona(a)
test.functionb('abc')
It errors out with "AttributeError: 'str' object has no attribute 'functiona'" Unable to call it with self. However, if I provide test.functiona(a) it works fine.
Few of other code samples works with self.function, how to solve this issue
Upvotes: 1
Views: 2968
Reputation: 91039
test.functionb('abc')
is a function call on the class, not on an instance.
I suppose it works if you do test().functionb('abc')
?
The difference is:
self = 'abc'
, a string. This string hasn't a method functiona()
.self
is set to the instance you just created – and you get an error because it doesn't know where to pass the 'abc'
.Upvotes: 1
Reputation: 141
Problem lies in the call test.functionb('abc'). You are not using object of the class to call the method. So, the self parameter is not passed. Python considers, the first parameter to be self, and you passed 'abc' which is a string.
Use it like test().functionb('abc') , then the default first argument becomes the object of test - like functionb(test_ob, 'abc').
Upvotes: -1
Reputation: 1458
you can add the decorator @classmethod
and then call it like you did
class test:
def __init__(self):
pass
@classmethod
def functiona(self, a):
b = a+0
print(b)
@classmethod
def functionb(self):
a = 5
self.functiona(a)
>>> test.functiona(1001)
>>> 1001
>>> test.functionb()
>>> 5
Upvotes: 1
Reputation: 8868
Problem lies in the call test.functionb('abc')
. You are not using object of the class to call the method. So, the self
parameter is not passed.
Python considers, the first parameter to be self, and you passed 'abc'
which is a string.
Use it like test().functionb('abc')
, then the default first argument becomes the object of test
- like functionb(test_ob, 'abc')
.
Upvotes: 1