我试图在python3中编写一个简单的递归函数。当我学习OO Java时,我也想编写涉及对象的python代码。这是我的代码,如下所示。我提示用户输入一个数字,屏幕应显示每个小于5的整数。
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 5 2015, 21:12:44)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from Recursion import *
>>> a = Recursion()
>>> a.main()
Enter a number for recursive addition: 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ZycinG/Desktop/Python Practice/Recursion.py", line 9, in main
recursive(x)
NameError: name 'recursive' is not defined
然而,当我在终端上运行它时,它会说:&#34; NameError:name&#39; recursive&#39;未定义&#34;。这是错误的样子:
markdown
这是什么原因造成的?我知道如何编写递归函数,给它一个参数,让它在终端上运行。但我想练习OOP。
答案 0 :(得分:4)
考虑您在全局范围内定义了函数:
def recursive(x):
if (x>5):
print (x)
recursive(x - 1)
你只需在程序的其他地方使用recusive(10)
调用此函数,类似于函数内部,如果你在类中使用staticmethod
:
class Recursion:
@staticmethod
def recursive(x):
if (x>5):
print (x)
recursive(x - 1) #this isn't how you call it any more
现在它作为Recursion.recursive
存储在全局范围内,因此您也必须在函数中引用它:
class Recursion:
@staticmethod
def recursive(x):
if (x>5):
print (x)
Recursion.recursive(x - 1)
但是,如果您希望方法可以直接访问类范围(在函数本地),则可以将其标记为classmethod
:
class Recursion:
@classmethod
def recursive(cls,x): #the first argument is the class
if (x>5):
print (x)
cls.recursive(x - 1)
这有几个好处,首先它可以被称为Recursion.recursive(10)
或x = Recursion() ; x.recursive()
,但是如果合适的话它将使用子类而不是始终使用Recursion
:
class Recursion:
def __init__(self,x=None):
raise NotImplementedError("not intended to initialize the super class")
@classmethod
def recursive(x):
if (x>5):
print (x)
cls.recursive(x - 1)
else:
return cls(x)
class R_sub(Recursion):
def __init__(self,x):
self._val = x
#now using R_sub.recursive(10) will work fine
虽然即使你不使用staticmethod
或classmethod
,你仍然需要引用该方法,作为一种方法:(在java中你可以使用这些方法,但python基本上强迫你使用方法self.METHOD
类似于java的this.METHOD
)
class Recursion:
def recursive(self,x):
if (x>5):
print (x)
self.recursive(x - 1)
希望这能解决方法如何在python中运行的方法!