0

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.

asked Feb 21, 2019 at 17:43
1
  • 4
    The last three lines shouldn't be indented, they are at the moment part of addData Commented Feb 21, 2019 at 17:44

2 Answers 2

3

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)
answered Feb 21, 2019 at 17:45
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the answer, do you know any good tutorial from where I can learn Python
@Developer Codecademy has a good starter course, it won't teach you programming, but it will teach you Python syntax and structure quite well
Codeacademy Python 2 course it's free and really helpful to know the basics. This course introduced me to programming so yes I recommend it very much ;)
2

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()
answered Feb 21, 2019 at 17:45

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.