在python中创建一个新类型 [英] Create a new type in python
问题描述
在 Python 3.x 中有没有办法创建一个新类型?我只能找到在 C++ 中做到这一点的方法.(顺便说一句,我的意思不是添加/编辑语法)
基本上我想做的是创建一个词法分析器,在那里我扫描输入,python 已经可以做 int 和 string,但是如果我想要另一种数据类型,例如 name,我该如何分配它以便我可以做...
示例:
# 这个是可以的a =字符串"类型(一)><类,'str'># 我怎样才能做到这一点?b = 我的名字类型(我的名字)><类,'名称'>
你会想要这样的东西,class
.在源代码中,您在 Python 中看到的所有对象类型都采用 class
形式.
输出与您预期的略有不同的原因是因为 class
的名称是 myName
所以这就是 type() 返回的代码>.我们还在
class
名称之前得到 __main__.
因为它是当前模块的本地名称.
Is there a way in Python 3.x to create a new type? I can only find ways to do it in c++. (I don't mean adding/editing syntax by the way)
Basically what I want to do is create a lexer, where I scan input and python can already do int and string, but if I want another datatype such as name, how could I assign it so that I can do...
Example:
# This can be done
a = "string"
type(a)
> <class, 'str'>
# How can I do this?
b = myName
type(myName)
> <class, 'name'>
You would want something like this, a class
. In the source code all of the object types you see in Python are in class
form.
>>> class myName:
... def __init__(self, name):
... self.name = name
... def __str__(self):
... return self.name
...
>>> b = myName('John')
>>> type(b)
<class '__main__.myName'>
>>> print(b)
John
The reason the output is slightly different to what you expected is because the name of the class
is myName
so that is what is returned by type()
. Also we get the __main__.
before the class
name because it is local to the current module.
这篇关于在python中创建一个新类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!