Python 的嵌套 类

Python's nested classes

我在使用 Python 的嵌套 类 时遇到问题。这是我设置代码的方式:

class Player:

    class Doll2:
        def __init__(self, stats):
            self.role = stats[0]
            self.level = float(stats[1])
            self.hp = float(stats[2])
            self.strength = float(stats[3])
            self.skill = float(stats[4])
            self.agility = float(stats[5])
            self.constitution = float(stats[6])
            self.charisma = float(stats[7])
            self.intelligence = float(stats[8])
            self.armor = float(stats[9])
            self.damage_min = float(stats[10])
            self.damage_max = float(stats[11])
            self.resilience = float(stats[12])
            self.critical = float(stats[13])
            self.block = float(stats[14])
            self.healing = float(stats[15])
            self.threat = float(stats[16])


    def __init__(self, name, server, province):
        stats2 = get_info_doll(province, server, name, "2")
        self.Doll2(stats2)

player1 = Player("Username", "us", "1")

print(player1.Doll2.hp)

这是我遇到的错误:

AttributeError: class Doll2 has no attribute 'hp'

我做错了什么?

self.Doll2(stats2) 创建了一个 Doll2 的实例,但没有将它绑定到 player1 的任何属性。你需要做:

 def __init__(self, name, server, province):
        stats2 = get_info_doll(province, server, name, "2")
        self.attributename = self.Doll2(stats2)

hp 是实例的属性(不是 class) 试试这个:

class Player:

    class Doll2:
        def __init__(self, stats):
            # ... more assignments
            self.hp = float(stats[2])
            # ... more assignments


    def __init__(self, name, server, province):
        stats2 = get_info_doll(province, server, name, "2")
        self.doll2 = self.Doll2(stats2)  # create instance of Doll2

player1 = Player("Username", "us", "1")
print(player1.doll2.hp)  # using instance instead of class

重要的几行是:

self.doll2 = self.Doll2(stats2)

print(player1.doll2.hp)