变量内部的Python和变量

时间:2018-05-14 19:53:57

标签: python class object

我有这个对象Troll。 我随机选择了他的武器'。 每次他出现他的武器都会改变。 在他的对象状态部分下,我有一个变量' base_att'我希望它是他的武器中的伤害变量' 如何通过'武器更新base_att变量?变量random.choice 请注意,我列出了我所有的武器'在另一个.PY文件中,items.weapon_for_troll调用。

class stick:
    name = 'Wooden Stick'
    damage = range (0,3)
    effect = None  

class rocks:
    name = 'Rocks'
    damage = range (0,5)
    effect = None

class troll:
    name = 'Troll'

class equipment:
    weapon = random.choice(items.weapon_for_troll)

class inventory:
    loot = None

class status:
    level = 1
    exp_point = 30
    hp_point = 30
    base_att = 
    base_def = 2
    bonus_def = 0

1 个答案:

答案 0 :(得分:1)

您需要区分(“静态”)类变量和(“非静态”)实例变量。

你宣称一切都是静止的 - 这对所有巨魔之间共享的东西很有用(就像怪物的“类型” - 也就是巨魔) - 对于所有“拥有”但不是“相同”的东西来说都不是那么好 - 像库存一样说。

尝试这种方法:

import random

class Weapon: # no need to make each weapon its own class
    def __init__(self,name,damage,effect):
        self.name = name
        self.damage = damage
        self.effect = effect    

# create some troll weapons to choose from
troll_weapons = [ Weapon("Wooden Stick", range(3), None), Weapon("Rocks",range(5), None) ]

class Equipment:
    def __init__(self):
        # every time you instantiate a new equipment, generate a random weapon
        # for this instance you just created. They are not static, they differ
        # between each Troll (who instantiates its own Equipment)
        self.weapon = random.choice(troll_weapons)

class Troll:    
    name = 'Troll'
    def __init__(self):
        self.equipment = Equipment() # get a new instance of Eq for this troll
                                     # instance
        self.weapon = self.equipment.weapon  # "link" the troll weapon to its equipment
                                             # as shortcut - do smth similar to an 
                                             # instance of your "Stat" block

    def __str__(self):
        return f"Troll with: {self.weapon.name}"

# create a troll army
trolls = [Troll() for _ in range(10)]
for t in trolls:
    print(t)

输出:

Troll with: Rocks
Troll with: Wooden Stick
Troll with: Rocks
Troll with: Rocks
Troll with: Wooden Stick
Troll with: Rocks
Troll with: Wooden Stick
Troll with: Wooden Stick
Troll with: Wooden Stick
Troll with: Wooden Stick

读取检查:

Classes
Class variables vs Instance variables

旁注:

  • 有关于命名方案的约定,类以Capital开头,成员小写