Create a new type in python
Solution 1
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.
Solution 2
You might have a look at Metaclasses: http://eli.thegreenplace.net/2011/08/14/python-metaclasses-by-example/
However, what exactly do you want to achieve?
user3324343
Updated on July 12, 2022Comments
-
user3324343 almost 2 years
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'>