1

Is it possible to create user defined data types in python without using class, like using structure. Please explain, because I am new in python. Thank You

1 Answers1

0

To create a type without using a class statement, you can use the type builtin:

class type(name, bases, dict)

With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and is copied to a standard dictionary to become the __dict__ attribute. For example, the following two statements create identical type objects:

class X:
    a = 1

X = type('X', (object,), dict(a=1))

See also Type Objects.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • Hey @wjandrea Thanks. –  Aug 15 '20 at 05:25
  • This *creates a class*, it's exactly equivalent to the class definition statement as explained in the document you are quoting – juanpa.arrivillaga Aug 15 '20 at 06:18
  • @juanpa I interpreted the question as "without using a class *statement*". That's the only way it makes sense to me. I edited the answer to clarify my assumption. – wjandrea Aug 15 '20 at 16:42