Accessing class properties and behaviour outside the class.


class Car:
    
    
    def __init__(self,color,company_name,price,seating_capacity):
        self.color = color
        self.company_name = company_name
        self.price = price
        self.seating_capacity = seating_capacity
    def forward(self):
        print("car is moving in forward direction")
    def reverse(self):
        print("car is moving in backward direction")



car_object = Car("blue","Tata","3Lakh","7")

# Accessing properties of class outside the class
print(car_object.color)
print()
print(car_object.company_name)
print()
print(car_object.price)
print()
print(car_object.seating_capacity)
print()

# Accessing methods of class outside the class.
car_object.forward()
print()
car_object.reverse()


Output:

blue

Tata

3Lakh

7

car is moving in forward direction

car is moving in backward direction

After creating an object, you can access the class properties and behavior by using object name followed by dot operator (.) followed by properties name/ instance variable/behavior/method name.

Syntax: object_name.properties or object_name.behavior

In the above example, we have created one object of class Car called car_object and for accessing properties we are using car_object.price (properties/ Instance variables) and for accessing methods we are using car_object.forward() (method) and so on.

Leave a Comment

Your email address will not be published. Required fields are marked *