thevengefulco
thevengefulco

Reputation: 309

Python Inheritance Issue

I have a class that is inheriting from another class, and I get the issue:

Traceback (most recent call last):
  File "main.py", line 45, in <module>
    class Player(Entity):
  File "main.py", line 53, in Player
    self.image = pygame.image.load('sam_stand.png')
NameError: name 'self' is not defined

These are the classes:

class RigidBody(object):
    def __init__(self, (x, y), size, mass=1):
        self.x = x
        self.y = y
        self.size = size
        self.mass = mass
        self.thickness = 0
        self.angle = 0
        self.drag = 1
        self.elasticity = 0.9

class Player(Entity):
    """Player class.  Provides all player variables and methods"""
    def __init__(self):
        RigidBody.__init__(self)
        self.grounded = True
        self.direction = "Right"
        self.axis = "Down"
        self.jump_counter = 0
        self.image = pygame.image.load('sam_stand.png')

How come self is recognized for all the other attributes for the Player, except for self.image? If I change it to image = pygame.image.load('sam_stand.png') the problem goes away.

Upvotes: 0

Views: 101

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121196

You are mixing tabs and spaces. When looking at your first revision source I see this:

enter image description here

Your method body is indented with tabs, which Python expands to 8 spaces. The last line, however, is indented with spaces only. You have your editor set to 4 spaces per tab, so you cannot see this mistake.

As a result, the self.image line falls outside the __init__ method. It is part of the class definition instead.

You really want to configure your editor to indent with spaces only.

Run your code with python -tt scriptname.py and fix all the errors that reports. Then run the tabs-to-spaces feature in your text editor (converting to 4 spaces) and then configure it to use spaces for indentation (automatically inserting 4 spaces when you use the tab key).

Using spaces for indentation is recommended by the Python styleguide for a reason, after all.

Upvotes: 4

Related Questions