它给了我一个错误,我被指示并初始化了变量type
,但是我在这里没有发现任何问题。你知道吗
对于此任务,使用名为_type
的实例变量创建一个类Dinosaur
。你知道吗
创建一个名为getType()
的getter方法,返回恐龙的类型。你知道吗
创建一个名为setType()
的setter方法来设置其类型。你知道吗
class Dinosaur:
def __init__(self,type):
self.type=type
def setType(self,type):
self.setType=type
def getType(self):
return self.type
# Create three dinosaurs
d1 = Dinosaur()
d2 = Dinosaur()
d3 = Dinosaur()
# Set their types
d1.setType("T-Rex")
d2.setType("Velociraptor")
d3.setType("Stegosaurus")
# Print the types
print(d1.getType())
print(d2.getType())
print(d3.getType())
构造函数接受一个参数:
因此,您应该使用该参数创建对象:
否则你会得到你提到的位置参数错误。你知道吗
或者可以将构造函数更改为将
type
初始化为空字符串或None
或类似内容:另外,setter也有问题,应该是
self.type=type
而不是self.setType=type
您可以在构造函数中添加默认值,这使得您的参数是可选的。你知道吗
然后您可以:
或传递参数:
相关问题 更多 >
编程相关推荐