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
Advertisement
Answer
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:
- In your case, you call the function object on the class. As it is not a staticmethod or classmethod, it is called with
self = 'abc', a string. This string hasn’t a methodfunctiona(). - In my case, the call operates on a class instance. Here,
selfis set to the instance you just created – and you get an error because it doesn’t know where to pass the'abc'.