用特殊符号调用对象 python 3

Call an object with special symbols python 3

我有一个关于 Python 如何知道某些事情的问题。例如,当我写

a_list = ["car", "plane"]
print(a)

Python 知道 a_list 是一个列表。这是如何运作的? python?

默认模块写在什么地方

我想创建一个有点像列表的对象,但是当我想获取特定位置的项目时,我想写

object_list[0]

而不是像

这样的方法
object_list.obtain_item(0)

我想创建一个对象来做类似

的事情
$"car", "plane"$
# like yo do ["car", "plane"] by default

而且我无法从列表继承,因为它在我正在处理的项目中被禁止。

这可能吗?我在这里和互联网上搜索,但我什至无法用文字表达我的问题以正确搜索。

要回答您的第一个问题,那将是实施 __getitem__ 方法的结果。

class Foo():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __getitem__(self, ind):
        if ind == 0:
            return self.x
        return self.y

x = Foo(1, 2)
print(x[0])
1

print(x[1])
2

请注意,这是一个非常简单的实现,我没有使用列表,因为你说你不能使用它。

要回答你的第二个问题,这将涉及更改该语言的基本语法和语法,作为该语言的最终用户,你目前无权这样做。

Python knows that a_list is a list. How does that work? where is it written in the default modules of python?

Python 解释器识别 list 文字,然后创建一个列表对象。 Python 列表对象是 "standard types that are built into the interpreter".

的一部分

I want to create an object that works kind like a list, but when i want to obtain the item in a specific position, i would want to write

您可以使用 object.getitem(self, key) 来做到这一点。网上有很多有用的例子。

And i would want to create an object doing something like

$"car", "plane"$

like yo do ["car", "plane"] by default

如果你不想改变 Python 解释器,你可以有一个 less "native/hardcore" 解决方案来解析字符串并自己创建你想要的对象,比如:

>>> def my_parser(s):
...     return [i.strip('"') for i in s.strip('$').split(', ')]
... 
>>> my_parser('$"car", "plane"$')
['car', 'plane']
>>>