在今天的讲座中,我们开始使用Python中的子类进行工作。作为一个例子,我们得到的代码类似于一个非常基本的社交网络,这是如下:Python子类属性错误
class socialNetwork:
class node:
def __init__(self, name, friendList):
self.name=name
self.friendList=friendList
def __init__(self):
self.nodeList=[]
def addPerson(self, name, friendList):
person=self.node(name,friendList)
self.nodeList.append(person)
s = socialNetwork()
s.addPerson("John",["Alice","Bob"])
s.addPerson("Alice",["John","Bob","Jeff"])
s.addPerson("Bob",["John","Alice","Jeff","Ken"])
s.addPerson("Jeff",["Alice","Bob","Barbra"])
s.addPerson("Ken",["Bob","Barbra"])
s.addPerson("Barbra",["Jeff","Ken"])
for person in s.nodeList:
print("name: ",person.name, "\n\t friends: ",person.friendList)
但是,每当我试图运行它,我收到以下消息:
Traceback (most recent call last):
** IDLE Internal Exception:
File "C:\Users\Mike\AppData\Local\Programs\Python\Python36-
32\lib\idlelib\run.py", line 460, in runcode
exec(code, self.locals)
File "C:/Users/Mike/AppData/Local/Programs/Python/Python36-32/run.py",
line 15, in <module>
s.addPerson("John",["Alice","Bob"])
AttributeError: 'socialNetwork' object has no attribute 'addPerson'
简而言之,我不知道为什么我遇到这个错误,特别是在教授运行相同的代码之后。我在这里错过了什么,如果有的话可以请人指出吗?
你确定这段代码是正确的吗?每个类应该只有一个'__init'方法。这里'node'有两个,'socialNetwork'也没有。 – GLR
这不是一个*子类*,它是一个*嵌套类*,在这里没有什么意义。 –