我有以下代码:
class Class1(object):
def say_my_name(self):
super(self.__class__, self).__init__()
print 'I am a class1'
def how_are_you(self):
print 'how are you from class1'
self.say_my_name()
class Class2(Class1):
def say_my_name(self):
super(self.__class__, self).__init__()
print 'I am a class2'
def how_are_you(self):
print 'how are you from class2'
self.say_my_name()
# all right
c1 = Class1()
c2 = Class2()
c1.how_are_you()
c2.how_are_you()
# attempt one. I expect 'I am a class1' but I get 'I am a class2'
c3 = super(Class2, c2)
c3.how_are_you() #
# attempt two. I expect 'I am a class1' but I get 'I am a class2'
Class1.how_are_you(c2)
正如您在我的测试代码中看到的那样。
我期望通过多态获得对基类的引用,方法how_are_you()
的调用返回我是class1 ,但我得到我是class2
我做错了什么?
EDIT 12/06/2016 15:47
更现实的例子
class Sheet(object):
def mergeArrayInColumns(self, startRow, startColumn, dimRows, dimColumns, separator=None):
# bla, bla, bla...
return True
def mergeColumns(self, startColumn, columns, separator=None):
self.mergeArrayInColumns(0, startColumn, self.rowCount(), columns, separator)
class CommandMergeColumns(QUndoSelectionCommand):
def __init__(self, sheet, startRow, rows, separator, undoSelection, redoSelection):
description = 'merge {} rows at [{},:]'.format(rows, startRow)
super(CommandMergeColumns, self).__init__(description, undoSelection, redoSelection)
# get a base class?!
self.sheet = super(CommandSheet, sheet)
self.startRow = startRow
self.rows = rows
self.separator = separator
def redo(self):
self.redoArray = self.sheet.getArray(self.startRow, 0, self.rows, self.sheet.columnCount())
# the problem it's here
self.sheet.mergeColumns(self.startRow, self.rows, self.separator)
# with this work but I do not like solution
#self.sheet.mergeArrayInColumns(self.startRow,
# 0,
# self.rows,
# self.sheet.columnCount(),
# self.separator)
def undo(self):
self.sheet.removeColumns(self.startRow, 1)
self.sheet.insertColumns(self.startRow, self.redoArray)
class CommandSheet(QObject, Sheet):
def mergeColumns(self, startColumn, columns, separator, undoSelection, redoSelection):
command = CommandMergeColumns(self, startColumn, columns, separator, undoSelection, redoSelection)
self.stack.push(command)
# and finally I call mergeColumns method...
document = CommandSheet()
document.mergeColumns(startColumn, count, None, undoSelection, redoSelection)