Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call a method from another method?

I am coding a program in python. I introduce an entire number and the program gives back to me the decomposition in prime factors of this number. For example 6 ---> 3, 2. Another example 16 --> 2, 2, 2, 2.

I am doing it with OOP. I have created a class (PrimeFactors) with 2 methods (is_prime and prime_factor_decomposition). The first method says wether the number is prime, and the second gives the decomposition back.

This is the code:

class PrimeFactors(object):
    def __init__(self, number):
        self.number = number

    def is_prime(self):
        n = self.number - 1
        a = 0
        loop = True

        if self.number == 1 or self.number == 2:
            loop = False

        while n >= 2 and loop:
            if self.number % n != 0:
                n -= 1
            else:
                a += 1
                loop = False
        return a == 0

    def prime_factor_decomposition(self): 
        factors = [] 
        n = self.number - 1
        loop = True

        if PrimeFactors.is_prime(self.number):
            factors.append(self.number)
            loop = False

        while n >= 2 and loop:
            if self.number % n == 0 and PrimeFactors.is_prime(n):
                factors.append(n)
                self.number = self.number / n
                if self.number % n == 0:
                    n += 1
            n -= 1
        return factors

s = PrimeFactors(37)
print(s.is_prime())

I am getting a mistake. I think it is something related to the method call. My question is, How can I call a method from another method if they both are from the same class?

like image 752
pablo casanovas Avatar asked Oct 15 '25 10:10

pablo casanovas


2 Answers

You need to use self. to call another method of the same class:

class Foo:
    def __init__(self):
        pass

    def method1(self):
        print('Method 1')

    def method2(self):
        print('Method 2')
        self.method1()
like image 147
MrAlexBailey Avatar answered Oct 17 '25 01:10

MrAlexBailey


Jkdc's answer is absolutely correct. I also wanted to note that your method calls are going to be problematic. You defined is_prime to take self as its only argument, but when you call it, you're passing in self.number or n.

If you need is_prime to work with arbitrary numbers, and not just whatever the class was initialized with, you should add an extra argument.

like image 20
MPlanchard Avatar answered Oct 17 '25 01:10

MPlanchard