Reputation: 6350
I am trying to call a function of a class in python but when i am trying to access the function i am unable to do that. I have started learning Python so i am not able to figure out what wrong i am doing here. Below is the python code:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
print(self.name + " Age is :" + str(self.age))
def addData(self):
print("Print hello..!!!")
p1 = Person("TestName", 36)
p1.myfunc();
p1.addData();
I want to print the age and name of the person but i am not getting any error or outpout.
Upvotes: 0
Views: 334
Reputation: 106543
You should instantiate an instance of the class outside the class block:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
print(self.name + " Age is :" + str(self.age))
def addData(self):
print("Print hello..!!!")
p1 = Person("TestName", 36)
p1.myfunc()
p1.addData()
Upvotes: 2
Reputation: 534
I reformatted your code and it works:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
print(self.name + " Age is :" + str(self.age))
def addData(self):
print("Print hello..!!!")
p1 = Person("TestName", 36)
p1.myfunc()
p1.addData()
Remember than in Python identation is very important, and also ;
is not needed at the end of lines.
In python, the semicolon is used to put several Python statements on the same line, for instance:
print(x); print(y); print(z)
Upvotes: 3