Python / PyGame使用类/方法创建具有随机属性的随机怪物

时间:2018-03-28 06:42:28

标签: python pygame

我正在尝试创建基于文本的RPG。我想使用Class Monsters来创建一个特定类型的随机怪物。但是,我似乎无法访问与类中的方法关联的随机变量。这是代码的精简版本:

import random

class Monsters():

    def wolfEnemy(self):
        self.hp = random.randint(10, 20)
        self.attk = random.randint(1, 3)
        self.gold = random.randint(2, 5)
        self.xp = 100

monsters = Monsters()

print(monsters.wolfEnemy)

things = monsters.wolfEnemy.hp()

print(things)

我不确定如何从实例化方法中访问变量。 print(monsters.wolfEnemy)只会None产生things = monsters.wolfEnemy.hp()builtins.AttributeError: 'function' object has no attribute 'hp'错误。有没有办法调用wolfEnemy和类/方法之外的属性。

2 个答案:

答案 0 :(得分:1)

定义一个继承自WolfEnemy类的Monster类。在Monster类中,您可以定义每个子类应具有的属性和方法,并覆盖它们以创建特定的子类。

import random


class Monster:

    def __init__(self):
        self.hp = random.randint(10, 20)
        self.attk = random.randint(1, 3)
        self.gold = random.randint(2, 5)
        self.xp = 100


class WolfEnemy(Monster):

    def __init__(self):
        # Call the __init__ method of the parent class, that means the
        # wolf instance will get the attributes that we've defined there.
        super().__init__()
        # To override specific attributes, assign new values here.
        self.hp = random.randint(20, 30)


wolf = WolfEnemy()
print(wolf.hp)

答案 1 :(得分:0)

你可以得到你想要的结果:

import random

class Monsters():
    def wolfEnemy(self):
        self.hp = random.randint(10, 20)
        self.attk = random.randint(1, 3)
        self.gold = random.randint(2, 5)
        self.xp = 100


monsters = Monsters()
# wolfEnemy() for the function call not wolfEnemy
monsters.wolfEnemy()
# monsters.hp get the attr not monsters.wolfEnemy.hp()
print(monsters.hp)