I\'m trying to define a simply Fraction
class
And I\'m getting this error:
python fraction.py
Traceback (most recent call last):
File
You are using numerator
as both a method name and a name for an instance attribute. Since methods are stored on the class, when you lookup that attribute you get the number, not the method. (Python will look up attributes on the instance before looking at the class.)
That is to say that on the line where you say f.numerator(2)
, it looks up f.numerator
and finds that it is 0
, then tries to call that 0
, which obviously shouldn't work.
If you have any practical purpose for this code, you can use the stdlib fractions
module: http://docs.python.org/library/fractions.html
Rational
type.A more practical default value for denominator
is probably 1
. (That way Fraction(5)
would be five, not some undefined operation tending towards infinity.)
Rather than a prints
method, it would be more typical to define __str__
and just print your object.
Your methods are just getting and setting an attribute. In Python, we generally do not use getters and setters—we just let users set our attributes.
It wouldn't hurt to inherit numbers.Rational
(Python 2.6 and up), which lets your class automatically do several things numbers are expected to. You will have to implement everything it needs you to, but then it will automatically make a lot more work. Check out Check out http://docs.python.org/library/numbers.html to learn more.
Spoiler alert:
class Fraction(object):
"""Don't forget the docstring....."""
def __init__(self, numerator=0, denominator=1):
self.numerator = numerator
self.denominator = denominator
def __str__(self):
return "%d / %d" % (self.numerator, self.denominator)
# I probably want to implement a lot of arithmetic and stuff!
if __name__ == "__main__":
f = Fraction(2, 5)
# If I wanted to change the numerator or denominator at this point,
# I'd just do `f.numerator = 4` or whatever.
print f