7

I'm writting a Fraction class and I am trying to use gcd(a,b) in the initialization of a Fraction object. However, when I was trying to do this it would not work WITHOUT the Fraction part of Fraction.gcd(a,b). I used @staticmethod here, but it does absolutely nothing, i.e. my code works the same without it.

Is there anyway I can call gcd without putting Fraction. in front of it? In Java I would normally create a static method and then just call it. I could very easily put the GCD code inside of the init, but I am trying to learn here!

I am missing a lot here. Can anyone explain: static methods, helper methods in a class and pretty much how I can use various methods inside of a class?

class Fraction(object):
    def __init__(self, a, b):
        if Fraction.gcd(a, b) > 1:
            d = Fraction.gcd(a, b)
            self.num = a/d
            self.denom = b/d
        else:
            self.num = a
            self.denom = b

    @staticmethod    
    def gcd(a,b): 
        if a > b: a,b = b,a
        while True:
            if b % a == 0: return a
            a, b = b%a, a

    def __repr__(self):
        return str(self.num) + "/" + str(self.denom)
1
  • 3
    Yeah, this isn't Java, functions can exist outside a class. Oct 5, 2011 at 21:07

5 Answers 5

11

Don't forget, in Python not everything needs to be in a class. There's nothing about gcd that makes it better-suited to being a class method than a standalone function: so take it out of the class. Now you can just call gcd(a, b).

4
  • 1
    Better to say "a method on a class" or "static method" since "class method" has a specific meaning and it's not a class method.
    – agf
    Oct 5, 2011 at 21:10
  • "Method" already implies it's in the class. Non-method functions are just "functions". And +1, staticmethod is largely useless in Python. Oct 5, 2011 at 21:19
  • If I created an object from the class, but the function was outside that class would it still work? In other words, if I put gcd outside the Fraction class, but created a fraction, would it still compute the gcd even though its not inside the class that's being instantiated? To generalize this, are these functions outside of the class that are still accessed by the class still able to be used by the class when instantiated?
    – mergesort
    Oct 6, 2011 at 2:27
  • Yes, why not? As long as the code is in the same module, or imports it. It's where the code is that matters, not where you're running it. Oct 6, 2011 at 6:22
8

Think of methods in a class just like any other class attribute -- reference them on self:

def __init__(self, a, b):
    if( self.gcd(a,b) > 1):
        d = self.gcd(a,b)

It doesn't matter whether it's an instance method, class method, or static method.

While you certainly can use a staticmethod if you want to keep the code associated with the class, it's usual in Python to use a module-level function, in which case you can call it as gcd:

def gcd(a,b): 
    if a > b: a,b = b,a
    while True:
        if b % a == 0: return a
        a, b = b%a, a

class Fraction(object):
    def __init__(self, a, b):
        if( gcd(a,b) > 1):
            d = gcd(a,b)
0
5

If you have a big method within your class that requires many calls to a static method you can define a local function object and assign the method to it so you can call this function instead.

For Static Method gdc:

class Fraction(object):    
    def __init__(self, a, b):
        gcd = Fraction.gcd
        if( gcd(a,b) > 1):
            d = gcd(a,b)
            self.num = a/d
            self.denom = b/d
        else:
            self.num = a
            self.denom = b

    @staticmethod    
    def gcd(a,b): 
        if a > b: a,b = b,a
        while True:
            if b % a == 0: return a
            a, b = b%a, a

    def __repr__(self):
        return str(self.num) + "/" + str(self.denom)

For Instance Method gdc:

class Fraction(object):    
    def __init__(self, a, b):
        gcd = self.gcd
        if( gcd(a,b) > 1):
            d = gcd(a,b)
            self.num = a/d
            self.denom = b/d
        else:
            self.num = a
            self.denom = b

    def gcd(self,a,b): 
        if a > b: a,b = b,a
        while True:
            if b % a == 0: return a
            a, b = b%a, a

    def __repr__(self):
        return str(self.num) + "/" + str(self.denom)

So

gcd = Fraction.gcd

and

gcd = self.gcd

will allow you to call (without Fraction at the beginning as per your request :))

gcd(a,b) 

Also, if you want some basic examples of python classes and instance/static methods have a look at some of my blog posts, specially the one called "Factorial and Fibonacci in Jython":

http://carlosqt.blogspot.com/search/label/Jython

1
  • @Boris "Improving" the whitespacing of code is risky at best (with a possible exception for indentation). Changing the code (i.e. deleting pairs of ()) goes beyond what editing should do.
    – Yunnosch
    Jun 9, 2019 at 5:32
1

I think you are referring to Java's "import static" feature. Just to clarify: as Java enforces object orientation, it cannot have "modules" like other languages. So using import static Math.*; for example will make all static methods on Math available to be called without the class name. In Python you can just add this function outside a class and call it.

0

That's how static methods work. You call them via Classname.methodname() (or via instance.methodname(), but self won't be available inside the method).

What you want is a regular function on the module level. Define it outside the class and do not decorate it.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.