数组python中字符串的含义是什么

2024-09-23 20:23:10 发布

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

“CmdBtn['menu']=CmdBtn.菜单“最后一行的意思是。你知道吗

def makeCommandMenu():
    CmdBtn = Menubutton(mBar, text='Button Commands', underline=0)
    CmdBtn.pack(side=LEFT, padx="2m")
    CmdBtn.menu = Menu(CmdBtn)
    ...
    ...
    CmdBtn['menu'] = CmdBtn.menu
    return CmdBtn

Tags: textdef菜单buttonleftsidepackcommands
3条回答

首先,在Python中everything is an object和方括号表示这个对象是可下标的(例如tuplelistdictstring等等)。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'])

当您使用x[y] = z时,它会调用__setitem__方法。你知道吗

x.__setitem__(y, z)

在你的例子中,CmdBtn['menu'] = CmdBtn.menu意味着

CmdBtn.__setitem__('menu', CmdBtn.menu)

Menubutton类确实提供了^{} method。它看起来像是用来为给定的键('menu')设置“资源值”(在本例中是CmdBtn.menu)。你知道吗

这不是“数组中的字符串”。你知道吗

括号运算符用于某种序列(通常是list,或tuple)、映射(通常是dict,或字典)或其他某种特殊对象(例如这个MenuButton对象,它不是序列或映射)中的项访问。与其他一些语言不同,在python中,任何对象都可以使用这个操作符。你知道吗

list类似于其他语言中的“数组”。它可以包含任何类型的对象的混合物,并保持对象的顺序。list对象对于维护对象的有序序列非常有用。可以使用list中的对象的索引访问该对象,如下所示(索引从零开始):

x = [1,2,3] # this is a list
assert x[0] == 1 # access the first item in the list
x = list(range(1,4)) # another way to make the same list

当您想将值与键关联时,dict(dictionary)很有用,这样您就可以稍后使用键查找值。像这样:

d = dict(a=1, b=2, c=3) # this is a dict
assert x['a'] == 1 # access the dict
d = {'a':1, 'b':2, 'c':3} # another way to make the same dict

最后,您可能还会遇到同样使用同一项访问接口的自定义对象。在Menubutton情况下,['menu']只访问响应键'menu'的某个项(由tkinterapi定义)。您也可以使用item访问创建自己的对象类型(下面的python 3代码):

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!

相关问题 更多 >