如何从另一个方法调用一个方法? [英] How do I call a method from another method?
问题描述
我正在用 python 编写程序.我引入一个整数,程序将这个数字的质因数分解返回给我.例如 6 ---> 3, 2. 另一个例子 16 --> 2, 2, 2, 2.
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.
我正在用 OOP 做这件事.我创建了一个具有 2 个方法(is_prime
和 prime_factor_decomposition
)的类(PrimeFactors
).第一种方法表示数字是否为素数,第二种方法返回分解.
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.
这是代码:
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?
推荐答案
需要使用self.
来调用同一个类的另一个方法:
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()
这篇关于如何从另一个方法调用一个方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!