[Python] How do I use Class Attributes, Arguments and "self." effectively in Python?

Discussão em 'Python' iniciado por Stack, Junho 17, 2025.

  1. Stack

    Stack Membro Participativo

    I am creating a text-based adventure game (as mentioned in this post), and I am stuck on how to use Classes and their attributes, arguments related to classes, and the pre-defined keyword self.. I have looked around for how to use them, but to no avail. I will give an example of each, with a question attached to them:

    class Player:
    def __init__(self, name):
    self.name = name
    self.maxhealth = 100
    self.health = self.maxhealth
    self.attack = 15
    self.money = 0

    def display(self, name):
    print("Name:",self.name,"\nHealth:",self.health,"/",self.maxhealth,"\nAttack Damage:",self.attack,"\nMoney:",self.money)


    Someone from the answers suggested changing self.name = name to self.name = None, but they didn't explain why or how it would help. If anyone could tell me how to define self.name in the correct or most efficient way, please do. I would also like to know how to call it in later functions.

    I am confused on how class attributes work (related to previous question), and how you know if they are enabled, and how to call them.

    I am also unsure of the arguments that would go into class Player(#here):, and how they could be used. I'm not sure if there are any uses to it, but I have seen people do (object) and (Edum #or something like that) and I don't know what they add, how to call them etc.

    import time
    import random
    import sys
    import pickle

    class Zombie:
    def __init__(self, name):
    self.name = name
    self.maxhealth = 50
    self.health = self.maxhealth
    self.attack = 5
    self.golddrop = random.randint(5,10)

    class Skeleton:
    def __init__(self, name):
    self.name = name
    self.maxhealth = 75
    self.health = self.maxhealth
    self.attack = random.randint(5,10)
    self.golddrop = random.randint(5,10)


    class Friend:
    def __init__(self, name):
    self.name = name
    self.maxhealth = 100
    self.health = self.maxhealth
    self.attack = random.randint(7,10)


    class DungeonBoss:
    def __init__(self, name):
    self.name = name
    self.maxhealth = 150
    self.health = self.maxhealth
    self.attack = random.randint(15, 25)


    Those are the classes I want in my game. I am wondering whether I can make a class just called "enemies" and then maybe make sub-sets/classes that can then be called from that class (once again, any help with how to call attributes from classes will be much appreciated), so it makes the code a lot cleaner.

    Please leave a comment if you are unsure about anything I just said, or if you need some more clarification with the questions. Thank you in advance.

    Continue reading...

Compartilhe esta Página