Python type() Built in Function

The type() function in Python is a built-in function that returns the class type of an object or creates a new type object.

Here are some examples of using the type() function:

# Example 1: Getting the type of an object
x = 10 # integer
y = "hello" # string
z = [1, 2, 3] # list
print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'str'>
print(type(z)) # Output: <class 'list'>

# Example 2: Creating a new type object
# syntax: type(name, bases, dict)

MyClass = type("MyClass", (object,), {"a":10, "b":20}) # same as class MyClass(object): a = 10; b = 20
obj = MyClass()
print(type(obj))
# Output: <class '__main__.MyClass'>
print(obj.a) # Output: 10
print(obj.b) # Output: 20

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Python float() Built in Function

Python bool() Built in Function

Python Printing Readable Results

Python exec() Built in Function