Python Forum
Trying to understand classes
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trying to understand classes
#1
I'm trying to get my head wraped around classes any help would be great.
Example code
class Game():
    def __init__(self):
        # code that will be running
        # I know this throws error
        # How do I get these vars
        print(playerX)
        print(playerY)

    def player(playerX, playerY):
        playerX = 480
        playeY = 50
        # More player stuff

def main():
    # code for main to work

if __name__ == "__main__":
    main()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#2
What are you having trouble with? If you are just having general trouble with classes, we have a class tutorial. Otherwise, a specific question about the problem you are having would be useful.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Getting the variables from player function to the init function
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#4
(Oct-26-2019, 08:33 PM)menator01 Wrote: Getting the variables from player function to the init function
It's the other way around.
Think of __init__ as a way to bring stuff in from outside into the class when instantiate(make the object).
Think you should look at tutorial that @ichabod801 posted and other OOP tutorials about classes to get the basic in.

To make something that work.
class Game:
    '''Initializer - Instance attributes'''
    def __init__(self, player_x, player_y):
        self.player_x = player_x
        self.player_y = player_y

    def player(self, power=50):
        '''I am a method in class Game,not a function'''
        player_x = self.player_x + power
        return f'player_x has a power of {player_x}'
        # More player stuff
Test usage:
See that self act as transporter,so can use self.player_x in method player.
>>> obj = Game(480, 50)
>>> obj.player_x
480
>>> obj.player_y
50
>>> 
>>> obj.player()
'player_x has a power of 530'
>>> obj.player(150)
'player_x has a power of 630'
>>> obj.player(500)
'player_x has a power of 980'
Reply
#5
Ok, I'm starting to get it. Thanks for the help
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#6
Using the **kwargs then self.width = kwargs['width'] I can get the values I need. What I'm wanting to know is there a way I can get the keys and values out of the loop to use in the methods. I've been reading and searching for hours and there does not seem to be anything on this. Not that I can understand as of yet. I could put all the methods in the loop and get what I need but, is that wise? My understanding is that the keyword args
(**args) are for an undefined amount of variables. Is this correct?

Thanks for any help


myclass.py
import pygame
class Game:
    
    
    
    def __init__(self, **kwargs):
        '''self.width = kwargs['width']
        self.height = kwargs['height']
        self.r = kwargs['r']
        self.g = kwargs['g']
        self.b = kwargs['b']'''

        for key, val in kwargs.items():
            print("Key -> %s Value - > %s" % (key, val))





    def window(self):
        print("window")
        #global aglobal
        #aglobal = pygame.display.set_mode((self.width, self.height))
        #return aglobal


    def bgcolor(self):
        print("bgcolor")
        #return poop.fill((self.r, self.g, self.b))

    def bgimage(self):
        print("bgimage")
        #return pygame.image.load("../Python_Projects/Game2/images/space.png")
test.py

import pygame
from myclass import Game


pygame.init()

imgpath = "../Python_Projects/Game2/images/"

w = Game(width = 800, height = 600)
w.window()

n = Game(r = 30, g = 9, b = 90)
n.bgcolor()

def main():
    running = True
    while running:
        

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                

        #pygame.display.update()


if __name__ == "__main__":
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#7
It feels like you are doing everything you can to make your code more confusing. Sure, you can use kwargs and setattr to assign a batch of attributes to your class with a single loop. But then you can't tell what attributes the class has by looking at the code.

And there is no reason to use global in a class. Use self, it's like a global that exists only within the class. And then it's clear where it's coming from: it's coming from the attributes of the current instance. If you have global, you can only have one instance of your class. If it is something that is constant across all the instances of a class, use a class attribute, like bg_path in my following rewrite of your code:

import pygame


class Game:

    bg_path = "../Python_Projects/Game2/images/space.png"

    def __init__(self, width, height, r, g, b):
        self.width = width
        self.heigh = height
        self.r = r
        self.g = g
        self.b = b

    def window(self):
        print("window")
        self.window = pygame.display.set_mode((self.width, self.height))
        return self.window

    def bgcolor(self, poop):
        print("bgcolor")
        poop.fill((self.r, self.g, self.b))

    def bgimage(self):
        print("bgimage")
        self.bg = pygame.image.load(self.bg_path)
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#8
Ok this is what I finished with. Would this be acceptable coding?
Sorry if I've been difficult as I said in the first post, I'm trying to get my head around this stuff.
Correct me if I'm wrong, classes contain methods for transporting/handling data. You can group the data a paticular object. Like I been experimenting with. Anything containingg the background window can be stored and used or manipulated e.g."the background color or window size can be changed".
When getting ready to add a character to the window, I can create a class that will contain everything about this character. Start position, movement, abilities and so forth. All of these classes can be in the same file or another file. The file would have to be imported.
Is my analogy correct? All comments welcome. Final question, I should be able to do this without using the __init__, correct? I realize the coding would be a little different but, the argument passing would be along the same lines?

test.py

import pygame
from myclass import Game


pygame.init()

window = Game(width = 800, height = 600, r = 30, g = 10, b = 90)
window.window()
window.background()


def main():
    running = True
    while running:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                


        pygame.display.update()


if __name__ == "__main__":
window.py
import pygame
class Game:
    
    
    
    def __init__(self, width, height, r, g, b):
        self.width = width
        self.height = height
        self.r = r
        self.g = g
        self.b = b


    def window(self):
        window = pygame.display.set_mode((self.width, self.height))
        self.window = window
        window = window.fill((self.r, self.g, self.b))
        return window


    def background(self):
        bgimage = pygame.image.load("../Python_Projects/Game2/images/space.png")
        window = self.window.blit(bgimage, (0, 0))
        return window
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help me understand this... (Classes and self). Ceegen 15 8,260 Mar-31-2019, 10:41 PM
Last Post: Yoriz
Question Helping understand classes Miraclefruit 10 6,314 Nov-27-2017, 01:58 PM
Last Post: Windspar
  Using classes? Can I just use classes to structure code? muteboy 5 5,076 Nov-01-2017, 04:20 PM
Last Post: metulburr

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020