gpt4 book ai didi

tcl - 我们可以在 tclOO 中定义静态函数吗?

转载 作者:行者123 更新时间:2023-12-04 21:43:47 29 4
gpt4 key购买 nike

在 itcl 中,可以在允许的类中创建一个 proc

namespace eval ns {set ::ns::i 0}

::itcl::class clsTest {
set ::ns::i 0 ;
proc i {} {
return [incr ::ns::i]
}
}

clsTest::i
1

tclOO 对此有一些支持吗?

最佳答案

类(大部分)是 TclOO 中的普通对象,因此您可以执行诸如在类本身上创建实例方法之类的操作。这就是类声明上下文中的 self 的作用,它是一种强大的技术:

oo::class create clsTest {
self {
variable i
method i {} {
return [incr i]
}
}
}

之后,你可以做:

clsTest i
# ==> 1
clsTest i
# ==> 2
clsTest i
# ==> 3

请注意,newcreate 实际上 只是最普通的预定义方法(碰巧是用 C 语言实现的),但您可以添加几乎任何你想要的东西。当然 oo::class 继承自 oo::object

如果您要使类级方法也显示为可在实例上调用的方法,那么您才真正需要技巧。我真的不推荐它,但是转发方法是可能的:

oo::class create clsTest {
self { ... }
# This is actually the simplest thing that will work, provided you don't [rename] the class.
# Use the fully-qualified name if the class command isn't global.
forward i clsTest i
}

关于tcl - 我们可以在 tclOO 中定义静态函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37937649/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com