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'>
                The type() function is used to get the type of an object. Python type() function syntax is: type(object) type(name, bases, dict)
Python type() The type() function either returns the type of the object or returns a new type object based on the arguments passed.
Specify a Variable Type There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With