简体   繁体   English

在Python中调用类函数

[英]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. 我试图在python中调用类的函数,但是当我尝试访问该函数时,我无法做到这一点。 I have started learning Python so i am not able to figure out what wrong i am doing here. 我已经开始学习Python,所以我无法弄清楚我在这里做错了什么。 Below is the python code: 以下是python代码:

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 ; 请记住,比起在Python中进行识别非常重要,并且; 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: 在python中,分号用于将多个Python语句放在同一行上,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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