python类错误str对象没有属性(初学者)

时间:2015-01-30 01:47:31

标签: python-3.x

嗨,我应该创建知道并满足这个类的功能,但它一直给我不同的错误,所以我应该如何实际做到这一点?大多数情况下,我想知道如何实现已知功能,以便我自己完成剩下的工作。这是代码

class Person(object):
    '''
    The Person class implements a single person in network of people knowing each other. 
    '''

    def __init__(self, name):
        '''
        initializes a new person with the given name. The person initially has no friends.

        @param name: the name of the person created.
        '''

        self.name   = name
        self.friend = None

    def get_friend(self):
        '''
        Returns the immediate friend of this person.

        @return: the immediate friend (person-object) of this person.
        '''
        return self.friend


    def set_friend(self, friend):
        '''
        Sets the immediate friend of this person.
        '''
        self.friend = friend



    def knows(self, other):
        '''
        Tests if a person is connected to another by a path.

        @param other: the person-object in the other end of the path tested.
        @return: true if the persons are connected, false otherwise.
        '''

        if self.name==None:
            return False
        while self.name.get_friend() != self.name or self.name.get_friend() != None:
            self.name=self.name.get_friend()


        while other.get_friend(other) != other.get_name() or other.get_friend() != None:
            other=other.get_friend()

        if self.get_name() == other.get_name():
            return True
        else:
            return False

        # please implement me


    def meet(self, other):
        '''
        Tries to add a path connecting to persons.

        @param other: the other end of the connection being introduced (person-object).
        @return: true if and only if the persons were not previously connected.
        '''

        # please implement me

        if self.knows(other)==True:
            return False
        else:
            while self.name.get_friend() != self.get_name() or self.get_name() != None:
                self.name = self.get_friend()


            while other.get_friend() != other.get_name() or other.get_friend() != None:
                other=other.get_friend()

            self.name.set_friend(other.get_name)
            return True





    def get_name(self):
        '''
        Returns a string representation of this Person, containing the name of the person.

        @return: the name of the person.
        '''
        return self.name

1 个答案:

答案 0 :(得分:0)

我运行了你的代码,它执行时没有错误。我的猜测是other是一个字符串,在meet()knows()中,您调用other.get_friend(),这显然是字符串未定义的。

>>> mystring = ' '
>>> mystring.get_friend()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'get_friend'
>>> 

回复您的评论

您获得NoneType的原因是因为您要将other.get_friend()分配给其他人,otherself.friend分配给您设置为None的{​​{1}}你的__init__。在致电set_friend 之前,请尝试拨打other=other.get_friend()