简体   繁体   English

如何在函数中使用类变量?

[英]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.但无论如何,我已经在文本 RPG 上工作了大约一个星期,并且刚刚开始使用战斗系统,并且我拥有所有玩家和敌人的统计数据。

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.即使你可以看到在init中有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.在其他方法中使用像self.px这样的,或者如果你想像那样使用它,只能让它player().px而不是player.px 。因为你的类需要在使用它的任何变量或方法之前先初始化。

Better to access class variables in same class by using self as good practice.通过使用self作为良好实践,更好地访问同一类中的类变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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