Python和变量内部变量

2024-04-23 11:32:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个对象Troll。 我随机挑选了他的“武器”。 每次他出现他的武器都会变。 在他的目标状态部分,我有一个变量'base\u att',我想它是他的'武器'的伤害变量 如何让baseatt变量被'wealth'变量更新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

Tags: namenoneforbaseitemsrangerandomatt
1条回答
网友
1楼 · 发布于 2024-04-23 11:32:42

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

你宣布所有的东西都是静态的-这对于所有巨魔之间共享的东西是很好的(比如一个“类型”的怪物-又名巨魔)-对于所有“拥有”但不“相同”的东西不是很好-比如一个清单。你知道吗

尝试以下方法:

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

旁注:

  • 命名方案有约定,类以大写开头,成员以小写开头

相关问题 更多 >