Python的嵌套类

时间:2015-07-14 18:06:51

标签: python class oop nested

我在使用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'

我做错了什么?

2 个答案:

答案 0 :(得分:2)

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

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)

答案 1 :(得分:0)

//Card.h @interface Card : NSObject @property (strong, nonatomic) NSString *contents; @property (nonatomic, getter=isChosen) BOOL chosen; @property (nonatomic, getter=isMatched) BOOL matched; - (int)match:(NSArray *)otherCards; //Card.m #import "Card.h" @implementation Card - (int)match:(NSArray *)otherCards { int score = 0; for (Card *card in otherCards) { if ([card.contents isEqualToString:self.contents ]) { score = 1; } } return score; } @end 创建Doll2的实例,但不将其绑定到self.Doll2(stats2)的任何属性。你需要这样做:

player1