Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
141 views
in Technique[技术] by (71.8m points)

python - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...