【问题标题】:Silly Example But Type Errors?愚蠢的例子,但类型错误?
【发布时间】:2013-04-13 10:17:07
【问题描述】:
class Cat(object):
    def __init__(self,run,fast):
        self.run=run
        self.fast=fast

    def skip(self,to,store):
        return 'Cat'

class Dog(Cat):
    def __init_(self,run, fast,tongue):
        Cat.__init__(self,run,fast)
        self.tongue=tongue

    def skip(self,to,store,happier):
        return 'Doggy'
class Parent(object):
    def __init__(self,velocity):
        self.velocity=velocity

"""
velocity is a list of speeds or something. But it can 
be from dogs or cats. Fast is a single number
"""
class Owner(Parent):
    def __init__(self,smile):
        Parent.__init__(self,velocity)
        self.smile=smile
        self.jumper=[]

    def update(self):
        # velocity is a list of instances of cats and dog
        for number in self.velocity:
            if isinstance(number,Dog):
                number.skip(to,store,happier)
                self.jumper.append(number)
            if isinstance(number,Cat):
                 number.skip(to,store)
                self.jumper.append(number)

不断出现的问题是,如果我在 if 实例更新方法中转到第一个 if 语句,它一直给我一个类型错误,它说我只需要为 skip 而不是三个参数。但是我知道因为它在块中,所以我必须拥有的实例是 dog,它需要三个参数。为什么会一直出现这种类型的错误?

【问题讨论】:

  • 等等,你在运行中输入什么?
  • 运行可能是这样的:
  • 您可能会遇到错误,因为 Owner 没有以 run 开头的属性
  • 另外,你的堆栈跟踪是什么?看起来,你应该得到一个 AttributeError

标签: python class error-handling


【解决方案1】:

您没有向我们展示您收到的实际错误消息,但我假设您误解了它,它实际上是说您只传递了 两个 参数到一个期望三个的方法。具体来说,我希望问题不在于这个代码块:

if isinstance(number,Dog):
    number.skip(to,store,happier)
    self.jumper.append(number)

但紧随其后的是:

if isinstance(number,Cat):
    number.skip(to,store)
    self.jumper.append(number)

因为DogCat 的子类,所以Dog 的任何实例也是Cat 的实例。因此,如果numberDog,则第一个代码块将成功运行,然后,因为您使用if 而不是elif,第二个代码块将尝试执行,而 Python将尝试在Dog 上调用.skip(to, store),这不起作用,因为Dogskip 需要三个参数。

从这个人为的示例中不清楚您首先要做什么,但我怀疑解决问题的最佳方法是将第二个 if 更改为 elif 以便 Dogs不会被视为非DogCats。

【讨论】:

    【解决方案2】:

    您在这里得到的是一个派生类,它使用不同的签名(形式参数列表)覆盖基类方法。您可以在这里阅读一些相关信息:

    Python: Can subclasses overload inherited methods?

    也许您不应该在两个类中使用相同的方法名,因为这两种方法实际上不能互换。或者,您可以通过将额外参数作为*args**kwargs 使它们可互换,不需要在基类中使用这些额外参数,而是在派生类中使用它们。像这样的:

    class Cat(object):
        def skip(self,to,store,*args):
            return 'Cat'
    
    class Dog(Cat):
        def skip(self,to,store,happier):
            return 'Doggy'
    

    现在任何一个类都可以使用三个参数(加上 self)调用其方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      • 1970-01-01
      • 2020-05-13
      • 2019-03-08
      • 2018-03-25
      • 1970-01-01
      相关资源
      最近更新 更多