简体   繁体   中英

How to use a class variable in a function?

First of all I apologize if I have writen some word incorrectly - English is my second language.

But anyway I've been working on an text RPG for like a week and just started on an combat system and I have all of the player and enemy statistics in clases.

This is just part of my code but it's enough. So I have made a function which levels up my character.

class player:
    def __init__(self):
        self.name='Hero'
        self.lvl=1
        self.xp=0
        self.lvl_next=25
        self.str=1
        self.dex=1
        self.int=1

    def pl_level(self):
        Nstr=0
        Ndex=0
        Nint=0

        while player.xp>=player.lvl_next:
            player.lvl+=1
            player.xp-=player.lvl_next
            player.lvl_next=round(player.lvl_next*1.5)
            Nstr+=1
            Ndex+=1
            Nint+=1

        print('Level:', player.lvl)
        print('STR {} +{} DEX {} +{} INT {} +{}'.format(player.str, Nstr, player.dex, Ndex, player.int, Nint))
        player.str+=Nstr
        player.dex+=Ndex
        player.int+=Nint
        print('Exp: '+str(player.xp))
        print('To the next level: {}%'.format(int((player.xp/player.lvl_next)*100)))
        print('Next:', player.lvl_next)

But I don't know why it just does not work. I've tried to simplify my code because well maybe thats how i'll find the problem. But it just keeps shoving me this error.

Traceback (most recent call last):
File "F:\2XK_\Coding\Python\Python_Battle\Ulfberht\leveling_system.py", line 99, in <module>
pl_level()
File "F:\2XK_\Coding\Python\Python_Battle\Ulfberht\leveling_system.py", line 11, in pl_level
while player.xp>=player.lvl_next:
AttributeError: type object 'player' has no attribute 'xp'

Even tho you can see that in init there is self.xp.

So how can I fix this?

Use that like self.px inside other methods or else if you want to use like that only make it player().px instead of player.px .As your class needs to be to initialized first before using any of its variables or methods.

Better to access class variables in same class by using self as good practice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM