Table of Contents
This updated guide examines Type Function: Type ()() Function in Python and organizes the essential facts, background, and practical takeaways in clear American English.
Syntax
There are two different types of parameters that can be passed to the type () function, which are called single parameters and three parameters.
type(object)type(name, bases, dict)
- If the type of single parameter (object) is passed, the result will return the given object type.
- If the third parameter (name, bases, dict) is passed, it returns a new type object.
type () with a single object parameter (single parameter)
If the type of single parameter (object) is passed, the result will return the given object type.
Example: How to get the object type?
numberList = [1, 2]print(type(numberList))numberDict = {1: 'one', 2: 'two'}print(type(numberDict))class Foo:a = 0InstanceOfFoo = Foo()print(type(InstanceOfFoo))
Run the program, the result is:
If you want to test the object type, you can also use the Python function isinstance (), because isinstance () function is also responsible for checking whether the given object is an instance of the subclass.
type () with three parameters name, bases, dict (parameter three)
If the third parameter (name, bases, dict) is passed, it returns a new type object.
name: class name will become attribute __name__.bases: tuple of classes, corresponding to the __base__ attribute.dict: a dictionary contains namespaces for the class, corresponding to the __dict__ attribute.
Example: Create object type using type ()
o1 = type('X', (object,), dict(a='Foo', b=12))print(type(o1))print(vars(o1))class test:a = 'Foo'b = 12o2 = type('Y', (test,), dict(a='Foo', b=12))print(type(o2))print(vars(o2))
Run the program, the result is:
{'a': 'Foo', 'b': 12, '__weakref__': objects>, '__dict__':, '__module__': '__main__', '__doc__': None}{'a': 'Foo', 'b': 12, '__weakref__': objects>, '__dict__':, '__module__': '__main__', '__doc__': None} {'a': 'Foo', 'b': 12, '__weakref__': objects>, '__dict__':, '__module__': '__main__', '__doc__': None}{'a': 'Foo', '__module__': '__main__', 'b': 12, '__doc__': None}
In the above example, the vars () function is used to return the __dict__ attribute . __dict__ is used to store writable properties of the object.
See also: Built-in Python functions
FAQ
What is Type Function: Type ()() Function in Python about?
It provides a structured overview of type function, explains the main context, and highlights practical takeaways for readers.
Why does this topic matter?
Understanding the main concepts helps readers evaluate the issue, avoid common mistakes, and make better-informed decisions.
How should readers use this information?
Use the guidance as a practical starting point, confirm details that may have changed, and follow current product, safety, or security recommendations.
Reader Comments 0
Sign in with email or Google to join the discussion.