简体   繁体   中英

Python: instance has no attribute 5

I have a Class names Game. In the __init__ method I assigned each instance 3 attributes:

   class Game:
        def __init__(self):
            self.__players = []
            self.__num_of_players = 0
            self.__lop = LOP()

Now in my main method i do the following:

  for player in game.__players:
     ...

And I get the following error:

AttributeError: Game instance has no attribute '__players'

using __ mangles the name of the class into the attribute name, you'd have to access it like:

for player in game._Game__players:
    ...

but if you intend for it to be accessed outside of the class, then don't use the leading __

Alternatively you can expose __players through a property

class Game:
    def __init__(self):
         self.__players = []
         self.__num_of_players = 0
         self.__lop = LOP()

    @property
    def players(self):
        return self.__players

then

for player in game.players:
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM