如何从tablelist
继承我自己的班级?
此代码不起作用(命令inherit
上的失败)
package require tablelist
::itcl::class myTableList {
inherit ::tablelist
}
应该如何编写构造函数?
P.S。 tablelist
版本为4.8
感谢。
答案 0 :(得分:2)
虽然你不能从tablelist继承,因为它不是一个可继承的类,你可以包装它并在外面添加功能。在最简单的情况下 - 修改或添加方法 - 您只需使用委派即可完成。以下是(使用TclOO):
### This metaclass makes doing the construction look like standard Tk.
oo::class create WidgetWrapper {
# It's a metaclass, so it inherits from oo::class
superclass oo::class
method unknown {methodName args} {
# See if we actually got a widget name; do the construction if so
if {[string match .* $methodName]} {
set widgetName $methodName
# There's a few steps which can't be done inside the constructor but have to
# be at the factory level.
set obj [my new $widgetName {*}$args]
rename $obj $widgetName
# Tk widget factories *MUST* return the path name as the name of the widget.
# It *MUST NOT* be colon-qualified, and it *MUST* refer to a widget.
return $widgetName
}
# Don't know what's going on; pass off to standard error generation
next $methodName {*}$args
}
unexport new create unknown
}
### This does the actual wrapping.
WidgetWrapper create WrappedTablelist {
constructor {pathName args} {
# Make the widget and *rename* it to a known name inside the object's
# private namespace. This is magical and works.
rename [tablelist::tablelist $pathName {*}$args] widget
}
# Delegate unknown method calls to the underlying widget; if they succeed,
# bake the delegation in more permanently as a forward.
method unknown {methodName args} {
try {
return [widget $methodName {*}$args]
} on ok {} {
oo::objdefine [self] forward $methodName widget $methodName
}
}
}
然后您可以继承WrappedTablelist
并添加/定义您想要的行为。使用unknown
进行委托初始化有点乱,但是tablelist有很多方法,所以在这里列出它们会有点痛苦。
你可以在itcl中使用类似的方案,但我不太了解它。
答案 1 :(得分:1)
Tablelist不使用[incr Tcl](或Tcl的任何其他对象系统),因此不能继承。