在使用 Python 进行面向对象编程时,可能会遇到 “Feature is not defined” 的错误。通常,这意味着在代码中引用了一个不存在的类或方法。
- 解决方案
2.1 检查类名
首先,检查类名是否正确。确保类名已正确定义,并且在代码中已被导入。
2.2 检查方法名
检查方法名是否正确。确保方法已正确定义,并且在代码中已被导入。
2.3 类继承问题
在 Python 的类继承中,如果子类重写了父类的方法,则需要使用 super() 方法来访问父类的方法。确保在子类中正确地使用了 super() 方法。
2.4 代码例子
class Parent:
""" superclass for a Zoo of animals """
def __init__(self, kind, legs, age):
self.animalType = kind
self.legs = legs
self.age = age
def getanimal(self):
return self.animalType
def getlegs(self):
return self.legs
def getage(self):
return self.age
def __str__(self):
output = 'Kind of Animal {}, Number of legs {}, Age {} '.format(self.animalType, self.legs, self.age)
return output
def makeNoise(self):
return None
class Cub(Parent):
"""subclass of parent"""
feature = 'playful'
def __init__(self, animalType, legs, age, feature="playful"):
super().__init__(animalType, legs, age)
self.feature = feature
def getplayful(self):
return self.feature
def __str__(self,):
parentOutput = super().__str__()
output = 'cub traits {} {}'.format(
parentOutput, self.feature)
return output
def makeNoise(self):
if self.make_Noise is True:
print('ROAR')
print()
class babyTurtle(Parent):
"""subclass of parent"""
slow = "slow"
def __init__(self, animalType, legs, age, feature='slow'):
super().__init__(animalType, legs, age)
self.feature = feature
def getslow(self):
return self.feature
def __str__(self):
parentOutput = super().__str__()
output = 'babyTurtle traits {} {}'.format(
parentOutput, self.feature)
return output
def makeNoise(self):
if self.make_Noise is True:
print('do baby turtles even make noise?')
print('')
class marsupial(Parent):
"""subclass of Parent"""
def __init__(self, legs, age, animalType, feature='kanga jack is gonna kick you out'):
super().__init__(animalType, legs, age)
self.feature = feature
def getkanga(self):
return self.feature
def __str__(self):
parentOutput = super().__str__()
output = 'kanga traits {} {} '.format(
parentOutput, self.kanga)
return output
def makeNoise(self):
if self.make_Noise is True:
print('the name is Jack')
print('')
animal1 = Parent(kind, legs, age)
Zoo = []
Zoo.append(animal1)
answer = input("add another animal y/n: ")
if answer == question:
question = 'y'
elif answer == 'n':
kid1 = Cub(kind, legs, age, feature)
kid2 = babyturtle(kind, legs, age, feature)
kid3 = marsupial(kind, legs, age, feature)
print(Zoo)
print(kid1, True.makeNoise)
print(kid2, True.makeNoise)
print(kid3, True.makeNoise)
question = 'n'
else:
print("error")