2

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'
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Daniella
  • 71
  • 8
  • 1
    Please see https://www.python.org/dev/peps/pep-0008/#method-names-and-instance-variables - use of underscores has a conventional meaning in Python. – jonrsharpe Dec 11 '14 at 20:18

1 Answers1

3

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:
    ...
Community
  • 1
  • 1
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
  • Thank you! I only wanted to have a little nice coding style... :( – Daniella Dec 11 '14 at 20:11
  • @Daniella starting with a single underscore doesn't result in any mangling, but it signals to other programmers that they shouldn't be using that attribute outside of the class. If you want people to use the attribute directly, just don't prefix it and you'll be fine – Ryan Haining Dec 11 '14 at 20:12
  • @Daniella the reason you use a double-underscore is to explicitly say "Hey this variable is private and nobody needs access to it but the object itself." If you then want to EXPOSE access to it in a certain way, I'd make it a `property` as the answer suggests. – Adam Smith Dec 11 '14 at 20:14