Python object() Built in Function

The object() function in Python returns a new featureless object that has no attributes. It is a base class for all other classes in Python. The object() function can also be used to test if an object is an instance of a class.

Here are some examples of using object() function in Python:

Using object() to create a featureless object

# This example creates an object using object() and tries to access its attributes
obj = object()
print(obj)
# Output: <object object at 0x000001F8C9A6E0D0>
print(obj.name) # Output: AttributeError: 'object' object has no attribute 'name'

Using object() as a base class

# This example creates a class that inherits from object and adds some attributes
class Bike(object):
    def __init__(self ,name ,gear):
        self.name = name
        self.gear = gear


    def __str__(self):
        return f"{self.name} has {self.gear} gears"


# create objects of class Bike
bike1 = Bike("Mountain" ,21)
bike2 = Bike("Road" ,18)


print(bike1) # Output: Mountain has 21 gears
print(bike2) # Output: Road has 18 gears

Using object() to test for instances

# This example uses object() to check if an object is an instance of a class or not
class Animal(object):
    pass


class Dog(Animal):
    pass


class Cat(Animal):
    pass


a = Animal()
d = Dog()
c = Cat()


print(isinstance(a ,Animal)) # Output: True
print(isinstance(d ,Animal)) # Output: True
print(isinstance(c ,Animal)) # Output: True
print(isinstance(a ,Dog)) # Output: False
print(isinstance(d ,Cat)) # Output: False

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

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions