如何修复此 OOP 错误?

How to fix this OOP error?

我正在努力理解 python 哎呀。但这对我来说并不容易。因此我写了 python 以下程序程序 (ex.1) 的 OOP 程序 (ex.2) 但它无法正常工作并出现以下错误。

ex.1

def factorial(n):  
    num = 1   
    while n >= 1:  
        num = num * n  
        n = n - 1  
    return num   

f = factorial(3)  
print f # 6 

ex.2

class factorial:

    def __init__(self):


      self.num = 1

    def fact(self,n):
        while n>=1:
            num = self.num * n
            n = n-1
        return num

f = factorial()
ne= factorial.fact(3)
print(ne)

错误

Traceback (most recent call last):
  File "F:/python test/oop test3.py", line 13, in ne= factorial.fact(3)
TypeError: fact() missing 1 required positional argument: 'n'

使用您创建的实例调用方法:

f = factorial() # creates instance of the factorial class
ne = f.fact(3)

或者使用 class 本身调用而不赋值:

ne = factorial().fact(3) # < parens ()
print(ne)

你也有一个错误,你应该使用 self.num 否则你将永远得到 1 作为答案,所以:

class Factorial: # uppercase
    def __init__(self):
        self.num = 1
    def fact(self, n):
        while n >= 1:
            self.num = self.num * n # change the attribute self.num
            n -= 1 # same as n  = n - 1
        return self.num

如果你不 return 你的方法会 return None 但你仍然会增加 self.num 所以如果你不想 return 但想在调用方法后查看 self.num 的值,您可以直接访问该属性:

class Factorial:
    def __init__(self):
        self.num = 1

    def fact(self, n):
        while n >= 1:
            self.num = self.num * n
            n -= 1

ne = Factorial()

ne.fact(5) # will update self.num but won't return it this time
print(ne.num) # access the attribute to see it 

存在三个问题: 1)逻辑错误:num = self.num * n应该改成 到 self.num = self.num * n,这里的 num 是您正在创建的另一个变量。

2) 逻辑错误,但如果第一个被解决,它就会变成语法错误: return num 应该改为 return self.num

3) 语法错误:

f = factorial()
ne= factorial.fact(3)

应该改为 ne = factorial().fact(3)ne = f.fact(3)