我试图在python中调用类的函数,但是当我尝试访问该函数时,我无法做到这一点。我已经开始学习Python,所以我无法弄清楚我在这里做错了什么。以下是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();
我想打印此人的年龄和姓名,但没有出现任何错误或支出。
答案 0 :(得分:3)
我重新格式化了您的代码,它可以正常工作:
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()
记住,比起Python标识来说非常重要,并且在行尾也不需要;
。
在python中,分号用于将多个Python语句放在同一行上,例如:
print(x); print(y); print(z)
答案 1 :(得分:2)
您应该在类块之外实例化该类的实例:
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()