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'
1

1 Answer 1

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:
    ...
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! I only wanted to have a little nice coding style... :(
@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
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.