2017-09-18 11 views
0

오늘 강의가 진행되는 동안 우리는 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' 

간단히 말해 , 나는 왜이 오류가 발생했는지, 특히 교수가 똑같은 코드를 실행 한 후에는 어떻게 될지 잘 모른다. 내가 여기서 뭔가를 놓친 건가? 누군가 그렇다면 그것을 지적 해 줄 수 있을까?

+1

이 코드가 맞습니까? 각 클래스는 하나의'__init' 메소드 만 가져야합니다. 여기서'node'는 두 개가 있고'socialNetwork'도 없습니다. – GLR

+1

* 중첩 클래스 * 인 * 하위 클래스 *가 아니기 때문에 실제로 이해가되지 않습니다. –

답변

0

하위 클래스를 정의하지 않았습니다. 상속, 괄호 안에 부모 클래스 (들)을 넣어 파이썬에서 지정한 예 :

class Node: 
    pass 

class Leaf(Node): 
    # Leaf is a subclass of Node 
    pass 

"네트워크"와 "노드"정말 서브 클래스로 이해가되지 않지만, 하나가 다른의 composed해야한다 .

당신이 한 일은 node 클래스라는 하나의 속성을 가진 socialNetwork 클래스를 정의하는 것입니다. 따라서 AttributeError이 표시되는 이유는 socialNetworkaddPerson 속성이 없기 때문입니다.

1

클래스의 방향이 잘못되어 클래스에 addPerson 메서드가 없습니다. 그것은 다음과 같아야합니다

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) 

들여 쓰기 python에 문제가 않습니다. 단서가 잘못되었다는 것은 같은 레벨에 두 개의 __init__ 메소드가 있다는 것입니다.

0

첫째, nodesocialNetwork의 하위 클래스가 아니며 후자 내에 중첩 된 클래스입니다. 두 번째로 socialNetwork에는 실제로는 addPerson이라는 특성이 없지만 socialNetwork.node은 실제로 않습니다.