我根据我所在的类的骨架编写了以下代码,它基于类的概念。我编写了类并编写了main,但我不断得到同样的错误,类中的函数未定义,这是我的代码:
class Person:
population = 0
def __init__(self, name):
self.name = name
print ('Initializing' ,self.name)
Person.population += 1
def __del__(self):
print (self.name,"says bye.")
Person.population -= 1
if Person.population == 0:
print ('I was the last one.')
else:
print ('There is/are still',Person.population ,'person/persons left.')
def sayHi(self):
print("Hi, my name is ",self.name)
def howMany(self):
#Prints the current population.
print(Person.population)
#If there is only 1 person then it should print "I am the only one"
if Person.population == 1:
print("I am the only one")
#If there are 2 people for example , then print "We have 2 people here"
if Person.population == 2:
print("We have 2 people here")
def main():
# Step 1: Ask for names of 2 people
x=input("name of person one?")
y=input("name of person two?")
# Step 2: Initialize Person 1
init1=__init__(x)
# Step 3: Use function sayHi() for Person 1
init1.sayHi()
# Step 4: Use howMany() for Person 1
init1.howMany()
# Step 5: Initialize Person 2
init2=__init__(y)
# Step 6: Use function sayHi() for Person 2
init2.sayHi()
# Step 7: Use howMany() for Person 2
init2.howMany()
# Step 8: Say Hi to Person 1
# Step 9: Use howMany() for Person 1
init1.howMany()
# Step 10: Terminate Person 1
init1.__del__()
# Step 11: Terminate Person 2
init2.__del__()
main()
它不断产生错误NameError: name __init__ is not defined
任何人都可以告诉我为什么会发生错误吗?
答案 0 :(得分:2)
class Person:
population = 0
def __init__(self, name):
self.name = name
print ('Initializing' ,self.name)
Person.population += 1
def __del__(self):
print (self.name,"says bye.")
Person.population -= 1
if Person.population == 0:
print ('I was the last one.')
else:
print ('There is/are still',Person.population ,'person/persons left.')
def sayHi(self):
print("Hi, my name is ",self.name)
def howMany(self):
#Prints the current population.
print(Person.population)
#If there is only 1 person then it should print "I am the only one"
if Person.population == 1:
print("I am the only one")
#If there are 2 people for example , then print "We have 2 people here"
if Person.population == 2:
print("We have 2 people here")
def main():
# Step 1: Ask for names of 2 people
x=input("name of person one?")
y=input("name of person two?")
# Step 2: Initialize Person 1
init1= Person(x)
# Step 3: Use function sayHi() for Person 1
init1.sayHi()
# Step 4: Use howMany() for Person 1
init1.howMany()
# Step 5: Initialize Person 2
init2= Person(y)
# Step 6: Use function sayHi() for Person 2
init2.sayHi()
# Step 7: Use howMany() for Person 2
init2.howMany()
# Step 8: Say Hi to Person 1
# Step 9: Use howMany() for Person 1
init1.howMany()
init1 = None
init2 = None
main()
答案 1 :(得分:1)
__init__
在您的课程中定义。因此,您可以在课堂外拨打__init__
这样的功能main
。
答案 2 :(得分:0)
您正试图将__init__
称为全局函数。这是Person
的一种方法。尽管如此,您无需明确地致电__init__
。
你可以打电话。
init1 = Person(x)
此外,您也无需明确致电__del__
。当对象被垃圾收集时(在脚本的末尾),它将被自动调用。因此,您只需移除对__del__