Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Method Attribute Error In Python

Tags:

python-3.2

In .../CthuluPackage In CthuluCore.py, I have:

class Dice(object):
    @staticmethod
    def __RollSkillMenu():
        bonus=int(input("Bonus>"))
        penalty=int(input("Penalty>"))
        return Dice.RollSkill(bonus-penalty)

In CthuluSkills.py, I have

from CthuluPackage.CthuluCore import *
import inspect
class SkillCheckResult(object):
    def __init__(self,targetSkill):
        self.TargetSkill=targetSkill
        print(Dice)
        self.Roll=Dice.__RollSkillMenu()

When I attempt to create a SkillCheckResult, I get the message:

AttributeError: type object 'Dice' has no attribute '_SkillCheckResult__RollSkillMenu'

Which really confuses me, because as far as I know I'm not trying to call anything named Dice.SkillCheckResult_RollSkillMenu,I'm only trying to call Dice.RollSkillMenu. Why is python prepending this to my method call?

like image 794
Benjamin Avatar asked May 24 '26 20:05

Benjamin


1 Answers

Any name appearing within a class body that starts with two underscores and does not end with two underscores automatically gets _TheNameOfTheClass prepended to it. Methods or attributes so named are supposed to be class-internal; if you want to access them from subclasses or other external code, you have to add the _TheNameOfTheClass prefix manually.

It looks like __RollSkillMenu isn't supposed to be internal to the Dice class. If so, then don't make the name start with two underscores. Just use one, or if it's supposed to be part of the public interface, don't use any underscores at all. In fact, you may want to consider moving it out of the class entirely.

If it is supposed to be internal to the Dice class, then stop trying to access it from SkillCheckResult.

like image 145
user2357112 supports Monica Avatar answered May 26 '26 13:05

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!