Hello guest, if you read this it means you are not registered. Click here to register in a few simple steps, you will enjoy all features of our Forum.
Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] Beginning PyGame question about "self"
#1
Hello I am not sure how to really question my question if that makes sense. I am following metulburr's pygame tutorial and something I don't really understand is why when I make a class I have self. I have my example below but if someone could explain what self.*** actually does or clarify it simply that would help, also I see under the player class "def __init__" a lot why is __init__ commonly used?

class player:
    def __init__(self, screen_rect):
        self.image = pg.image.load('spaceship.png').contert()
        self.image.set_colorkey((255,0,255))
        self.rect = self.image.get_rect(center = screen_rect.center)

    def draw(self, surf):
        surf.blit(self.image, self.rect)
Quote
#2
self refers to the object. Without self they are local variables that disappear when method is returned.

__init__ is just a constructor. Player() = Player.__init__() .
99 percent of computer problems exists between chair and keyboard.
Quote
#3
self is required in instance methods which pertain to editing the object. Without self as the first argument, its just a class method, which does not pertain to the object.

When you assign something to self.var such as
self.image = pg.image.load('spaceship.png').contert()
self.image is a class attribute. Each object is going to have a separate copy. Which doesnt matter here as there is only one player. But you can use self.image in any class method in that class without passing argumetns back and forth....or using global keywords, etc. You can also call that attribute by the object via player.image

the dunder init method (or constructor) is the method that gets executed automatically when the object is created.
So doing
player = Player(my_args)
runs the dunder init method.
jakegold98 likes this post
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  [PyGame] Problem importing pygame / installing pygame Klar 4 548 Dec-16-2017, 05:48 PM
Last Post: Klar
  [Pygame] Avoid SentDex pygame tutorials georgecoopers 1 864 Apr-09-2017, 12:40 PM
Last Post: metulburr

Forum Jump:


Users browsing this thread: 1 Guest(s)