且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

类属性不会传递给对象

更新时间:2023-10-06 11:32:40

记住使用如您在其他 __的init __ 方法,使实例的属性。

 高清__init __(自我,名):
    self.name =名称
    self.hp ​​= 300
    ...
    self.weapon =无

另外,我觉得其他属性也应该是实例属性,也就是说,它们设置在 __的init __ 方法和使用,例如: self.wgt self.impact self.broken_bones 等等。

I'm trying to create a very basic RPG-like game where you select a character, give that character a weapon, and then tell it to attack another character with damage based on the stats of the character and the weapon. The weapon class belongs to a top level class called Equip. When I try to set an attack damage variable that incorporates the weapon's stats, however, I get:

'Char' object has no attribute 'weapon.'

I have the Char class weapon value set to None as default. But below, I have given the character (dean) a weapon by using dean.weapon = sword (which is a weapon). I've tried changing weapon.wgt to self.weapon.wgt but that doesn't seem to help.

See the pertinent parts of the code, leaving out the attack code because I don't think it's relevant to the question and will clutter up things, but I will if it's necessary.

I believe the code is a mess, so constructive critique will be appreciated.

Code:

class Char(object):

    def __init__(self, name):
        name = name
        hp = 300
        mp = 10
        strn = 1
        dmg = 1
        dex = 1
        armor = 0
        weapon = None

    attack_speed = dex

    intact_bones = ["right arm", "left arm", "right leg", "leg leg", "skull", "sternum", "nose"] # JUST ASSUME RIGHT SIDE IS PRIMARY SIDE FOR NOW

    broken_bones = [] ### define what to do per bone if bone is in this list

    dmg = strn * self.weapon.wgt


class Equip(object):
    wgt = 1
    desc = ""

    def __init__(self, name):
        self.name = name

class weapon(Equip):
    impact = 1
    sharp = 1

    def __init__(self, name):
        self.name = name

sword = weapon("Sword")
sword.wgt = 10
sword.impact = 6
sword.sharp = 7


dean.weapon = sword
dean.attack(hamilton)

Remember to use self, as in your other __init__ methods, to make attributes of the instance.

def __init__(self, name):
    self.name = name
    self.hp = 300
    ...
    self.weapon = None

Also, I think the other attributes should also be instance attributes, i.e., set them in the __init__ methods and use self, e.g. self.wgt, self.impact, self.broken_bones, etc.