UFatO
UFatO

Reputation: 3

Python's nested classes

I'm having trouble with Python's nested classes. Here's how I have the code set up:

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)

And here is the error that I'm getting:

AttributeError: class Doll2 has no attribute 'hp'

What am I doing wrong?

Upvotes: 0

Views: 141

Answers (2)

drgarcia1986
drgarcia1986

Reputation: 343

hp is an attribute of instance (not of class) try this:

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

The important lines is:

self.doll2 = self.Doll2(stats2)

and

print(player1.doll2.hp)

Upvotes: 2

txizzle
txizzle

Reputation: 840

self.Doll2(stats2) creates an instance of Doll2 but doesn't bind it to any attribute of player1. You need to do:

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

Upvotes: 0

Related Questions