python中类的继承与方法重写,Python,重写继承的类方法

I have two classes, Field and Background. They look a little bit like this:

class Field( object ):

def __init__( self, a, b ):

self.a = a

self.b = b

self.field = self.buildField()

def buildField( self ):

field = [0,0,0]

return field

class Background( Field ):

def __init__( self, a, b, c ):

super(Background, self).__init__( a, b )

self.field = self.buildField( c )

def buildField( self, c ):

field = [c]

return field

a, b, c = 0, 1, 2

background = Background( a, b, c )

This error is pointing to Field's buildField():

"TypeError: buildField() takes exactly 2 arguments (1 given)."

I expected Background init() to be called first. To pass "a, b" to Fields init(), Field to assign a and b then to assign a list with three 0's in it to field. Then for Background's init() to continue, to then call its own buildField() and override self.field with a list containing c.

It seems I don't fully understand super(), however i was unable to find a solution to my issue after looking at similar inheritance problems on the web and around here.

I expected behavior like c++ where a class can override a method that was inherited. How can i achieve this or something similar.

Most issues I found related to this were people using double underscores. My experience with inheritance with super is using the inherited class init() to just pass different variables to the super class. Nothing involving overwriting anything.

解决方案

Coming from a C++ perspective, there might be two misconceptions here.

First, overriding a method with a different signature does not overload it like in C++. If one of your Background objects tries to call buildField with no arguments, the original version from Field will not be called -- it has been completely hidden.

The second issue is that if a method defined in the superclass calls buildField, the subclass version will be called. In python, all methods are bound dynamically, like a C++ virtual method.

Field's __init__ expected to be dealing with an object that had a buildField method taking no arguments. You used the method with an object that has a buildField method taking one argument.

The thing with super is that it doesnt change the type of the object, so you shouldn't change the signature of any methods that the superclass' methods might call.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值