Access Properties of a Class Object in Python


Access Properties of Class Objects

We can access a property of a class object using dot operator. The expression to access the property of a class object is to specify the object name followed by dot operator followed by the property name.

For example, if object1 is a class object in Python, then the syntax of the expression to access its property property1 is

object1.property1

We can either read the value of this property, assign a new value to this property, or delete this property.

Example

Let us take an example scenario where we have a class named Person with two properties: name, age.

We create an object person1 of type Person, with some initial values for its properties: Person('Mike', 22).

Now, we shall read the property name and print it to output. Then we update the property name with a new value and print the property's value to output.

Python Program

class Person:
    def __init__(self, name="NA", age="0"):
        self.name = name
        self.age = age

person1 = Person("Mike", 22)

#read property value
personName = person1.name
print(personName) #Mike

#update property value
person1.name = "Mr. Mike"
print(person1.name) #Mr. Mike

Output

Mike
Mr. Mike

Summary

In this Python Classes and Objects tutorial, we learned how to access properties of a class object.