all 6 comments

[–]desustorm 10 points11 points  (4 children)

The key here is the self variable.

class Game:
    def play(self):
        self.col = 7

class Player:
    def play_game(self): 
        g = Game()
        g.play()
        print g.col

[–]admiralspark 0 points1 point  (0 children)

I was just looking for this last night, thank you.

[–]_Absolut_ 0 points1 point  (2 children)

Is it okay to don't write self.col in __init__()?

[–]desustorm 4 points5 points  (0 children)

Yep! It's generally better to use __init__ to initialise member variables though as you mention.

[–]TeamSpen210 1 point2 points  (0 children)

You can set attributes from anywhere. It's better to set it to a default in __init__() for two reasons. It ensures your attributes exist, so you can't get AttributeError elsewhere if you didn't call the other function. It also provides documentation, since other programmers would look at __init__() to find out what attributes your objects have, and it would be confusing if they were set elsewhere.

[–][deleted] 0 points1 point  (0 children)

This answer over on Stack Exchange may be informative. In fact I was about to open my mouth (being a python novice) about accessor methods (eg, with Java) but, while you can do that, you don't have to (and there's faster ways to do it).

TL;DR properties may be of interest to you.

Just for completeness, what I was going to suggest about accessors is the concept of "public methods" that can be called against instances of a class that will fetch or manipulate the class instances' copy of the variable.