0

Could you help me to find the problems?

I just add the object to one list, but it seems that it appears in another list!

class people(object):

    name = ""
    __adjacent = []
    position = 0

    def __init__(self,nam):
        self.name = nam
    def print_name(self):
        print self.name
    def get_adjacent(self): 
        return self.__adjacent
    def append_adjacent(self,people):
        self.__adjacent.append(people)


sis = people('sister')
bro = people('brother')
sis.append_adjacent(bro)
print len(bro.get_adjacent())
for i in bro.get_adjacent():
    i.print_name()  
print len(sis.get_adjacent())

Question: why there is a object in bro's adjacent list???

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
zhancr
  • 19
  • 2
  • try assigning `__adjacent = []` within `__init__` (i.e. `self.__adjacent = []`), as you do with `name` – Pynchia Oct 04 '15 at 08:48
  • BTW, several things are wrong/not optimal within your code. There's little need for getters/setters in python (see [this SO QA](http://stackoverflow.com/questions/6618002/python-property-versus-getters-and-setters)) – Pynchia Oct 04 '15 at 08:53
  • Also, you may want to define the `__str__` and/or `__repr__` methods and get rid of `print_name` (see [this SO QA](http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python)) – Pynchia Oct 04 '15 at 08:55
  • oh, you might want to make `pos` an instance attribute as you did with `name` and now with `__adjacent`, instead of a class atribute. See [here](http://stackoverflow.com/questions/206734/why-do-attribute-references-act-like-this-with-python-inheritance) for an example, but google some more of it and try some code yourself until you get it, it's important. – Pynchia Oct 04 '15 at 08:57
  • and name classes properly, i.e. `People`. See [PEP-8](https://www.python.org/dev/peps/pep-0008/) – Pynchia Oct 04 '15 at 09:01
  • 1
    Got it .Class attribute is just like a static member in C++ .You did help me a lot .thanks again! – zhancr Oct 04 '15 at 09:40

0 Answers0