我试图了解python oop。但这对我来说并不容易。因此,我为以下程序(ex.1)编写了python OOP程序(ex.2),但它无法正常工作并出现以下错误。
例1
def factorial(n):
num = 1
while n >= 1:
num = num * n
n = n - 1
return num
f = factorial(3)
print f # 6
例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)
或使用类本身进行调用而无需分配:
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
如果不返回,则方法将返回None,但仍将增加self.num,因此,如果您不想返回但想在调用该方法后查看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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句