我有以下代码:
class Person:
def __init__(self,name):
self.name = name
self.balance = 0
def setBalance(self, value):
self.balance = vale
def setName(self, name):
self.name = name
class Main:
def __init__(self):
self.people = []
def addPerson(self,name):
self.people.append(Person(name))
def updateBalance(self,balance,index):
self.people[index].setBalance(50)
print self.people[0]
main = Main()
main.addPerson("Jack")
main.updateBalance(30,0)
我编写了以下代码,以查看对象如何与数组一起工作。但是,当我尝试运行它时,出现 NameError:未定义名称'self'。我不确定自己在做什么错?
如果不清楚或需要修改,请在拒绝投票之前在评论中告知我。
非常感谢
答案 0 :(得分:1)
您还应该传递self
作为参数:
class Main:
def __init__(self):
self.people = []
def addPerson(self, name):
self.people.append(Person(name))
def updateBalance(self, balance,index):
self.people[index].setBalance(50)
print people[0] #no need for self if you are calling local variable of class but this will print an empty array
您还输入了错误
class Person:
def __init__(self,name):
self.name = name
self.balance = 0
def setBalance(self, value):
self.balance = vale --> not vale but value
def setName(self, name):
self.name = name
答案 1 :(得分:1)
您的代码有几个问题:
def ...(self, ...)
print(...)
是Python3中的一个函数,必须从一个方法中调用。以下调整使您的代码有效:
class Person:
def __init__(self, name):
self.name = name
self.balance = 0
def setBalance(self, value):
self.balance = value
def setName(self, name):
self.name = name
class Main:
def __init__(self):
self.people = []
def addPerson(self, name):
self.people.append(Person(name))
def updateBalance(self, balance, index):
self.people[index].setBalance(50)
print("Updating people at index %d" % index)
main = Main()
main.addPerson("Jack")
main.updateBalance(30, 0)
print (main.people[0])
打印:
Updating people at index 0
<__main__.Person instance at 0x100d065f0>
答案 2 :(得分:0)
尽管Java或C ++等语言在其方法定义中将“ self” /“ this”自变量隐式表示为 ,但Python将其自定义为 explicit 。因此,您的Main
类中的方法定义应如下所示:
class Main:
def __init__(self):
self.people = []
def addPerson(self, name):
self.people.append(Person(name))
def updateBalance(self, balance, index):
self.people[index].setBalance(50)
实际上,您以前拥有的是addPerson()
方法,该方法接受了呼叫者的零自变量...并且它已重命名 {{1} }到self
,这很不直观。按照约定,在Python中仅将方法的第一个参数称为“自我” ...您可以像这样轻松定义name
:
addPerson()
...它完全可以正常工作。