我收到了错误
“NameError:名称'is_palindrome'未定义”
我在网站上发现了这个简单的问题,要求创建一个名为Palindrome
的类,并在其中创建一个名为is_palindrome
的函数来检查给定的单词并返回True
,如果它是回文和False
,否则它应该使用类和静态方法完成(所以我无法删除它们)代码如下。
class Palindrome:
@staticmethod
def is_palindrome(s):
return len(s) < 2 or s[0] == s[-1] and is_palindrome(s[1:-1])
word = input()
print(Palindrome.is_palindrome(word))
我通过删除类声明等其他方法解决了这个问题
return word==word[::-1]
但是我试图用上面的代码来理解这个问题,为什么当我把它包含在一个类中时我得到了这个错误
“NameError:名称'is_palindrome'未定义”
虽然,我没有看到类中的方法或静态有何帮助,但这里是修复:
class Palindrome:
@staticmethod
def is_palindrome(s):
return len(s) < 2 or s[0] == s[-1] and Palindrome.is_palindrome(s[1:-1])
word = input("Enter your word: ")
print(Palindrome.is_palindrome(word))
OUTPUT:
Enter your word: ROTAVATOR
True
编辑:
如果你不想在课堂上纠结,假设你还没有其他事情在做:
def is_palindrome(s):
return len(s) < 2 or s[0] == s[-1] and is_palindrome(s[1:-1])
word = input("Enter your word: ")
print(is_palindrome(word))
编辑3:
其他方式:
class Palindrome:
def is_palindrome(self, s):
return len(s) < 2 or s[0] == s[-1] and self.is_palindrome(s[1:-1])
word = input("Enter your word: ")
p_Obj = Palindrome()
print(p_Obj.is_palindrome(word))
不需要Palindrome类。只是有
def is_palindrome(s):
return len(s) < 2 or s[0] == s[-1] and is_palindrome(s[1:-1])