Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new type in python [closed]

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'>
like image 684
user3324343 Avatar asked Mar 25 '14 15:03

user3324343


People also ask

What is type () function in Python?

The type() function is used to get the type of an object. Python type() function syntax is: type(object) type(name, bases, dict)

What does type () return in Python?

Python type() The type() function either returns the type of the object or returns a new type object based on the arguments passed.

Can you specify type in Python?

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.


2 Answers

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.

like image 177
anon582847382 Avatar answered Oct 21 '22 04:10

anon582847382


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?

like image 29
dorvak Avatar answered Oct 21 '22 04:10

dorvak