“恐龙”类的位置参数有问题

2024-09-24 02:24:36 发布

您现在位置:Python中文网/ 问答频道 /正文

它给了我一个错误,我被指示并初始化了变量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())

Tags: 实例方法self类型deftype错误types
2条回答

构造函数接受一个参数:

    def __init__(self,type):
        self.type=type

因此,您应该使用该参数创建对象:

d1 = Dinosaur('T-Rex')
...

否则你会得到你提到的位置参数错误。你知道吗

或者可以将构造函数更改为将type初始化为空字符串或None或类似内容:

def __init__(self):
    self.type = ''  # or None

另外,setter也有问题,应该是self.type=type而不是self.setType=type

您可以在构造函数中添加默认值,这使得您的参数是可选的。你知道吗

class Dinosaur:
    def __init__(self,type = None):
        self.type=type

然后您可以:

>>> d1 = Dinosaur()
>>> print(d1.getType()) 
None
>>> d1.setType("T-Rex")
>>> print(d1.getType()) 
"T-Rex"

或传递参数:

>>> d2 = Dinosaur("Velociraptor")
>>> print(d2.getType())
"Velociraptor"

相关问题 更多 >