如何正确扩展python中的类并使用父类?

如何正确扩展python中的类并使用父类?,python,python-2.7,Python,Python 2.7,我需要从SUDS模块扩展类Client。。。例如,我有一个简单的代码,可以很好地工作 client = Client(wsdl, username = USERNAME, password = PASSWORD, headers = {'Content-Type': 'application/soap+xml'}, plugins = [VapixHelper()]) rules = client.service.GetActionRules() 所以我需要为这个类添加一些额外的方法,所以我

我需要从
SUDS
模块扩展类
Client
。。。例如,我有一个简单的代码,可以很好地工作

client = Client(wsdl, username = USERNAME, password = PASSWORD, headers = {'Content-Type': 'application/soap+xml'}, plugins = [VapixHelper()])

rules = client.service.GetActionRules()
所以我需要为这个类添加一些额外的方法,所以我尝试这样做:

class Vapix(Client):
    def __init__(self, args):
        globals().update(vars(args))
        USERNAME, PASSWORD = user_data.split(':')
        super(Vapix, self).__init__(wsdl, username = USERNAME, password = PASSWORD, headers = {'Content-Type': 'application/soap+xml'}, plugins = [VapixHelper()])

    def setActionStatus(self, status):
        print super(Vapix, self).service.GetActionRules()
我得到的是这个错误,而不是结果:

Traceback (most recent call last):
  File "vapix.py", line 42, in <module>
    client.setActionStatus(True)
  File "vapix.py", line 36, in setActionStatus
    print super(Vapix, self).service.GetActionRules()
AttributeError: 'super' object has no attribute 'service'
回溯(最近一次呼叫最后一次):
文件“vapix.py”,第42行,在
client.setActionStatus(True)
setActionStatus中第36行的文件“vapix.py”
打印super(Vapix,self).service.GetActionRules()
AttributeError:“超级”对象没有“服务”属性

您没有重写
服务()
方法,因此不需要使用
super()
来查找原始方法;删除
super()
调用,直接在
self
上访问属性:

def setActionStatus(self, status):
    print self.service.GetActionRules()
super()
仅当需要在基类(按方法解析顺序,MRO)中搜索方法(或其他描述符对象)时才需要,这通常是因为当前类已重新定义了该名称

如果需要调用基类
foo
,但当前类实现了
foo
方法,则不能使用
self.foo()
,而需要使用
super()
。例如,您必须使用
super()
作为
\uuuuu init\uuuuu
;您的派生类有自己的
\uuuuu init\uuuuu
方法,因此调用
self.\uuuu init\uuuuuu()
将递归调用相同的方法,但
super(Vapix,self)。\uuuuu init\uuuuuuu()
工作是因为
super()
查看
self的MRO,在该顺序中找到
Vapix
,然后查找下一个具有
\uuuu init\uuu
方法的类


这里
service
是一个实例属性;它直接在
self
上定义,甚至不是一种方法。

只需使用
self.service
@BrenBarn nice one,谢谢。。。可能是,当需要调用父类时,您可以提供一些信息,说明
super(Vapix,self)
self
之间的区别在哪里?您可能想了解,您不是在那里调用父类,而是在访问实例的属性。只要你正确地调用超类方法(就像你在使用
\uuuuu init\uuuu
),正确的属性就会出现在实例上,你可以像平常一样使用它们。是的,已经理解了这一点。。。你的答案上有一个动作。。。如果我想重写父方法,我该怎么办?@Kirix:那么您可以将该方法命名为相同的名称,并使用
super()
仍然调用父方法。