Create a new type in python

python, python-3.x, types

Solution

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.

Problem

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'> ```

Original source