Call a class method in the same python class
I'm teaching oop in python, I ran into an error that I don't understand. I want to call the class method inside of it, but I get the error NameError: name 'self' is not defined
My code:
class Cat:
def __init__(self,name='Alex'):
self.name=name
def prnt(self):
print(self.name)
self.prnt()
p1=Cat()
0
1 answers
When creating an instance of the class, only __init__()
is executed, so you can add the necessary statement there:
def __init__(self, name='Alex'):
self.name = name
print(self.name)
If you want exactly the method of the class, then call it in __init__()
:
class Cat:
def __init__(self, name = 'Alex'):
self.name = name
self.prnt()
def prnt(self):
print(self.name)
0
Author: Эникейщик, 2020-04-21 11:08:52