用于移植到Python cod的Tcl面向对象扩展

2024-03-29 12:36:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为Linux构建一个状态栏。我已经制作了一个模块,用于插入不同的键盘时:

set initialTeck [eval exec cat [glob /sys/bus/usb/devices/*/product]]
set initialTeck [string match *Truly* $initialTeck]

set initialKB [exec xkb-switch] 

dict set table samy 0 samy
dict set table samy 1 temy
dict set table temy 0 samy
dict set table temy 1 temy
dict set table gb   0 samy
dict set table gb   1 temy


proc init {} {
    variable initialTeck
    variable initialKB
    set currentTeck [eval exec cat [glob /sys/bus/usb/devices/*/product]]
    set currentTeck [string match *Truly* $currentTeck]
    set currentKB [exec xkb-switch]
    if {$initialTeck != $currentTeck} {
        set initialTeck $currentTeck
        nextKB $currentKB $initialTeck 
    }
}

proc nextKB { currentKB teck } {
    variable table
    exec [dict get $table $currentKB $teck]
}
while 1 {
init
after 1000

}

Temy是一个.xkb布局文件,是我为“真正符合人体工程学的键盘”设计的,samy是一个标准GB键盘的自定义.xkb布局。Teck存储USB端口的状态和哈希表的dict。你知道吗

很明显,状态栏还有更多的模块,我已经使用了名称空间,但是随着项目越来越大,我决定采用面向对象的方法。同时,我需要将项目翻译成Python代码,以便在开发人员之间共享。你知道吗

目前tcl有许多面向对象的扩展;TclOO、Snit、Stooop、Incr tcl、Xotcl等等。因此,如果TCR TCL类似于C++,那么是否存在类似于Python的TCL扩展?你知道吗


Tags: 模块evaltable键盘variabledictexecset
1条回答
网友
1楼 · 发布于 2024-03-29 12:36:15

没有一个Tcl OO系统在风格上与Python完全相似;语言不同,支持不同的思考问题的方式。部分原因是语法(大多数Tcl程序员不太喜欢_字符)但其中更重要的一点是,Tcl OO系统的工作方式不同:

  • 它们不会垃圾收集值,因为所有值都有可以存储为普通字符串的名称。你知道吗
  • 它们没有允许截取基本操作的语言集成。你知道吗

最终的结果是,Tcl的OO系统都使对象的行为类似于Tcl命令(当然,这允许很大的灵活性),而不像Tcl值(通常是非常简单的透明数字、字符串、列表和字典)。这使得OO的风格与Python截然不同。你知道吗

你可以假装在最简单的水平,我想,但一旦你开始做任何复杂的事情,你会击中差异。更重要的是,我们需要选择一个更具体的例子来深入研究。你知道吗

以下是一些Python code

class Shape:

    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.description = "This shape has not been described yet"
        self.author = "Nobody has claimed to make this shape yet"

    def area(self):
        return self.x * self.y

    def perimeter(self):
        return 2 * self.x + 2 * self.y

    def describe(self, text):
        self.description = text

    def authorName(self, text):
        self.author = text

    def scaleSize(self, scale):
        self.x = self.x * scale
        self.y = self.y * scale

下面是TclOO中的等价类定义(我最喜欢):

oo::class create Shape {
    variable _x _y _description _author

    constructor {x y} {
        set _x $x
        set _y $y
        set _description "This shape has not been described yet"
        set _author "Nobody has claimed to make this shape yet"
    }

    method area {} {
        return [expr {$_x * $_y}]
    }

    method perimeter {} {
        return [expr {2 * $_x + 2 * $_y}]
    }

    method describe {text} {
        set _description $text
    }

    method authorName {text} {
        set _author $text
    }

    method scaleSize {scale} {
        set _x [expr {$_x * $scale}]
        set _y [expr {$_y * $scale}]
    }
}

除了明显的语法差异(例如,Tcl喜欢大括号并将表达式放在expr命令中),需要注意的主要事情是变量应该在类定义中声明,并且不需要传递self(它自动作为命令[self]呈现)。你知道吗

相关问题 更多 >