简体   繁体   中英

Call a class function in Python

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.

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)

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM