首先,在Python中everything is an object和方括号表示这个对象是可下标的(例如tuple、list、dict、string等等)。Subscriptable意味着这个对象至少实现了__getitem__()方法(在您的例子中是__setitem__())。你知道吗
使用这些方法很容易与类成员交互,所以不要害怕构建自己的示例,理解其他人的代码。你知道吗
请尝试以下代码段:
class FooBar:
def __init__(self):
# just two simple members
self.foo = 'foo'
self.bar = 'bar'
def __getitem__(self, item):
# example getitem function
return self.__dict__[item]
def __setitem__(self, key, value):
# example setitem function
self.__dict__[key] = value
# create an instance of FooBar
fb = FooBar()
# lets print members of instance
# also try to comment out get and set functions to see the difference
print(fb['foo'], fb['bar'])
# lets try to change member via __setitem__
fb['foo'] = 'baz'
# lets print members of instance again to see the difference
print(fb['foo'], fb['bar'])
class MyObject:
def __getitem__(self, x):
return "Here I am!"
这个对象除了返回与您给定的键或索引值相同的字符串外,没有什么作用:
obj = MyObject()
print(obj [100]) # Here I am!
print(obj [101]) # Here I am!
print(obj ['Anything']) # Here I am!
print(obj ['foo bar baz']) # Here I am!
首先,在Python中everything is an object和方括号表示这个对象是可下标的(例如
tuple
、list
、dict
、string
等等)。Subscriptable意味着这个对象至少实现了__getitem__()
方法(在您的例子中是__setitem__()
)。你知道吗使用这些方法很容易与类成员交互,所以不要害怕构建自己的示例,理解其他人的代码。你知道吗
请尝试以下代码段:
当您使用
x[y] = z
时,它会调用__setitem__
方法。你知道吗即
在你的例子中,
CmdBtn['menu'] = CmdBtn.menu
意味着Menubutton
类确实提供了^{'menu'
)设置“资源值”(在本例中是CmdBtn.menu
)。你知道吗这不是“数组中的字符串”。你知道吗
括号运算符用于某种序列(通常是
list
,或tuple
)、映射(通常是dict
,或字典)或其他某种特殊对象(例如这个MenuButton
对象,它不是序列或映射)中的项访问。与其他一些语言不同,在python中,任何对象都可以使用这个操作符。你知道吗list
类似于其他语言中的“数组”。它可以包含任何类型的对象的混合物,并保持对象的顺序。list
对象对于维护对象的有序序列非常有用。可以使用list
中的对象的索引访问该对象,如下所示(索引从零开始):当您想将值与键关联时,
dict
(dictionary)很有用,这样您就可以稍后使用键查找值。像这样:最后,您可能还会遇到同样使用同一项访问接口的自定义对象。在
Menubutton
情况下,['menu']
只访问响应键'menu'
的某个项(由tkinterapi定义)。您也可以使用item访问创建自己的对象类型(下面的python 3代码):这个对象除了返回与您给定的键或索引值相同的字符串外,没有什么作用:
相关问题 更多 >
编程相关推荐