1

我有一些课程:

class Window(object):
    def __init__(self, name):
        self.wind_name = name
    def getWindowName(self):
        return 'wnd' + self.wind_name

class Control(object):
    def __init__(self, name, wnd):
        self.contrl_name = name
        setattr(self, 'getWindowName', wnd.getWindowName)
        setattr(self, 'wind_name', wnd.wind_name)
    def getControlName(self):
        return (self.getWindowName(), 'unk' + self.contrl_name)

class Button(Control):
    def __init__(self, name, wnd):
        super(Button, self).__init__(name, wnd)
    def getControlName(self):
        return (self.getWindowName(), 'btn' + self.contrl_name)

wnd = Window('MyApp')
btnOK = Button('OK', wnd)
btnOK.getControlName() # work ok., return ('wndMyApp', 'btnOK')
btnOK.wind_name = 'NewApp'
btnOK.getControlName() # does not work properly., return ('wndMyApp', 'btnOK')

如何扩展课程Control| Button从类的对象Window访问对象中的函数和getWindowName字段?wind_namebtnOK

self.wnd = wnd有没有办法不用在 Control 类中创建字段,或者setWindowNameWindow...中添加方法?

我不能Control从类继承类Window!这不合逻辑。

4

2 回答 2

2

Python允许从多个类继承,即

class Button(Control, Window):
    ...

但是在这种情况下,您应该确切地知道自己在做什么(说到 Python 的方法解析顺序(MRO))。我推荐阅读这本小书:Python Attributes and Methods

于 2012-08-07T10:25:31.397 回答
0

您可以将属性用于属性

class Window(object):
def __init__(self, name):
    self.wind_name = name

def getWindowName(self):
    return 'wnd' + self.wind_name

class Control(object):
    def __init__(self, name, wnd):
        self.contrl_name = name
        self.wnd = wnd
        setattr(self, 'getWindowName', wnd.getWindowName)

    def get_wind_name(self):
        return self.wnd.wind_name
    def set_wind_name(self, v):
        self.wnd.wind_name = v

    wind_name = property(get_wind_name, set_wind_name)
    def getControlName(self):
        return (self.getWindowName(), 'unk' + self.contrl_name)

class Button(Control):
    def __init__(self, name, wnd):
        super(Button, self).__init__(name, wnd)
    def getControlName(self):
        return (self.getWindowName(), 'btn' + self.contrl_name)

wnd = Window('MyApp')
btnOK = Button('OK', wnd)
print btnOK.getControlName() # work ok., return ('wndMyApp', 'btnOK')
btnOK.wind_name = 'NewApp'
print btnOK.getControlName()
于 2012-08-07T10:37:04.030 回答