Ways to reach variables from one class to another class?
<p>I'm trying to create a basic game, but I'm fairly new to the python programming scene. I've come across a problem where with two classes (a player and enemy class), I want to access class variables like health from the player and enemy, and vice versa. What are some ways of doing this? </p>

<p>Here's the code to better emphasize what I'm asking:</p>

<pre><code>    class Player(object):
        def __init__(self, image):
            self.x = 100
            self.y = 240
            self.health = 30
            self.defense = 25
            self.image = image
            self.black = (0, 0, 0)
            self.draw()

        def draw(self):
            screen.blit(self.image, (self.x, self.y))
            line = pygame.draw.rect(screen, self.black, (80, 300, 100, 5))

        def attack(self):
            pass

    class Enemy(object):
        def __init__(self, image):
            self.x = 480
            self.y = 240
            self.health = 20
            self.defense = 15
            self.image = image
            self.black = (0, 0, 0)
            self.draw()

        def draw(self):
            screen.blit(self.image, (self.x, self.y))
            line = pygame.draw.rect(screen, self.black, (460, 300, 100, 5))

        def attack(self):
            pass
</code></pre>

<p>Basically, I don't understand how I can take something like the "self.health" from one class, and easily access it from the other class. I've tried some methods of using return methods etc., but I'm curious if there are any simple ways to do this. Help is appreciated!</p>

<p>This code creates a class, and in the special <code>__init__</code> method, it assigns values to various <em>member variables</em>.</p>

<pre><code>class Player(object):
    def __init__(self, image):
        self.x = 100
        self.y = 240
        self.health = 30
        self.defense = 25
        self.image = image
        self.black = (0, 0, 0)
        self.draw()
</code></pre>

<p>These member variables are also called <em>properties</em> in Python. If you have a reference to a Player instance (an instance of the Player class):</p>

<pre><code>p = Player()
</code></pre>

<p>You can access the properties all you like:</p>

<pre><code>print(p.health)
</code></pre>

<p>Perhaps you need some kind of "main loop" or controller class that has access to players and enemies and can set their properties accordingly:</p>

<pre><code>class MainLoop(object):

   def __init__(self):
     self.player_1 = Player()
     self.enemy_1 = Enemy()

   def run(self):
     if fight():   # fight() is some function of your game
       self.player_1.health -= 10
       self.enemy_1.health -= 20
</code></pre>

python pygame