I found a solution for this on here, but then I realized it was Python 2.7. I'm using Python 3.3.7, and I've recently been experimenting with classes, and I believe I may have ended up confusing myself. I have two files; my class file (Dice.py):
class Dice:
def __init__(self, sides):
self.sides = sides
@classmethod
def roll(self):
return self.sides 2
and my main file.
from Dice import Dice
Dice(int(input('How many sides are on the dice? ')))
print(Dice.roll())
Very simple for now, theoretically. However, I've been running into a strange attribute error that's had me stuck on these ten or so lines of codes for far longer than I'd care to admit. I keep receiving a "AttributeError: type object 'Dice' has no attribute 'sides' " each time I attempt to run the main file, which should theoretically give me an answer of the input amount 2.
I've gone through and initialized it multiple ways, added @classmethod, renamed the attribute and all of that; I just can't same to shake this error. I was wondering exactly what the error meant if it wasn't referring to the init function at the start, and how I could fix it so it can actually run. Thank you!
CodePudding user response:
The more idiomatic method to write a class method is
class Dice:
...
@classmethod
def roll(cls):
...
Note the parameter is usually called cls
, not self
. What the @classmethod
method does, is make it so that when you call Dice.roll()
, the 'instance' that's passed to the method is the object Dice
- literally, the class that owns the method (not any particular instance of the class). This is usually used in conjunction with inheritance and polymorphism.
Now, since __init__()
has never been called on the Dice
class itself (it would only ever be called on an instance of the Dice
class), the Dice
class does not ever have an attribute called sides
attached to it.
In your case, you probably want roll()
to be an instance method, and to save the new instance to a variable:
class Dice:
def __init__(self, sides):
self.sides = sides
def roll(self):
return self.sides 2
die = Dice(int(input('How many sides are on the dice? ')))
print(die.roll())
# alternatively
sides = int(input('How many sides are on the dice? '))
print(Dice(sides).roll())