单个类内的Python函数调用

2024-04-19 13:02:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把这两个函数放在同一个数学类中。使用数学 类对象。这两个我都能叫功能。和我也要菲波纳西系列来阵列内。你知道吗

#fibonacii series of a no using recursion
def fib(n):
    if n<=1:
        return n
    else:
        return (fib(n-1) + fib(n-2))

n = int(input("Enter number of terms:"))
print("Fibonacii series are: ")
for i in range (n):
    print(fib(i))

#for factorial
n=int(input("Enter the no to find factorial: "))
def facts(n):
    if n == 0 or n == 1:
        return 1
    if n>=1:
       return n * facts(n-1)
print("The facatorial of a given no",str(n),"is:",facts(n))

Tags: ofnoforinputreturnifdef数学
1条回答
网友
1楼 · 发布于 2024-04-19 13:02:29

我建议您使用静态方法创建一个类:

class Fibonacii(object):
   def __init__(self):
      # this is the constructor you can initialize stuff here if required
      # if not just pass it like in this example
      pass

   @staticmethod
   def fib(n):
    if n<=1:
        return n
    else:
        return (Fibonacii.fib(n-1) + Fibonacii.fib(n-2))

   @staticmethod
   def facts(n):
    if n == 0 or n == 1:
        return 1
    if n>=1:
       return n * Fibonacii.facts(n-1)

静态方法的优点是它们可以在不创建该类的对象的情况下使用。所以在你的剧本里你可以做到:

if __name__ == "__main__":
   n = int(input("Enter number of terms:"))
   print("Fibonacii series are: ")
   for i in range (n):
       print(Fibonacii.fib(i))

   #for factorial
   n=int(input("Enter the no to find factorial: "))
   print("The facatorial of a given no",str(n),"is:",Fibonacii.facts(n))

main之后的部分是脚本中正在执行的部分(如果它是主脚本)。请注意,该类从未用于创建对象。但它用于保存两个函数并可用于调用它们。你知道吗

相关问题 更多 >