You are currently viewing Python Class attribute Properties

Python provides a set of class attribute properties that are used to set, get and delete attributes from the class. After creating a Class in Object Oriented Programming in Python, these are some properties that are used to work with attributes on the class. Also, we can check whether a particular property exists or not.

Advertisements
  1. Set/Update the attribute of a class using setattr()
  2. Delete particular attributes of a class using delattr()
  3. Return the attribute of a class using getattr()
  4. Check whether a particular attribute exists or not using hasattr()

1. Quick Examples of attribute properties of a Class

The following example uses the above four discussed properties which will update, delete, display, and check whether an attribute exists or not.


# Create State class
class State:
  name = 'AP'
  population = 23000
  country="India"

# Object for the State class
data1 = State()

# Set name to 'TS' using setattr() which already exists.
setattr(data1, 'name', 'TS')

# Set country to 'India' using setattr() which doesn't exists.
setattr(data1, 'country', 'India')

# Return name using getattr()
getattr(data1,'name')

# Try to return phone using getattr() with default message
getattr(data1,'phone','phone Not exists')

# Try to return phone using getattr()
try:
    print(getattr(data1,'phone'))
except:
    print("phone attribute doesn't exist!")

# Delete population attribute using delattr()
delattr(State,'population')

# Does city attribute exists?
hasattr(State, 'city')

2. setattr() Property

The setattr() property is used to update the existing attribute value in the class. If the attribute doesn’t exist, it will create an attribute and a specified value is assigned.

2.1 setattr() property Syntax

Following is the syntax of the setattr() property.


# Syntax of setattr()
setattr(object, attribute, value)

Here, an object is the class instance, attribute can be new or existing, and value is assigned to the attribute.

2.2 setattr() property Parameters

  • The first parameter is the instance of the class (object).
  • The second parameter is the attribute name.
  • The third parameter is the value assigned to the attribute.

2.3 setattr() Examples

Example 1: Let’s create a class named State with attributes name, population, and country. All these attributes have some default values. When you create an instance of a class these default values are assigned to the class properties.

You can update the values of the class attributes by using the setattr() function.


# Create class
class State:
  name = 'AP'
  population = 23000
  country="India"

# Object for the State
data1 = State()

print("Actual Data:")
print("State Name: ",data1.name,"\n" ,"Population: ",data1.population,"\n" ,"Country: ",data1.country)

# Set name to 'TS' using setattr()
setattr(data1, 'name', 'TS')

print("Updated Data:")
print("State Name: ",data1.name,"\n" ,"Population: ",data1.population,"\n" ,"Country: ",data1.country)

This example yields the below output.

Python Class attribute Properties

By using the setattr(), we have updated the name attribute to ‘TS’. Previously it is set to default ‘AP’. When we display the data after the setattr(), the new attribute value is displayed.

3. getattr() property

The getattr() property is used to return the value of the specified attribute. It also takes three parameters.

If the attribute doesn’t exist, It will return AttributeError. We can handle this scenario in two ways.

  1. Specifying default message as a parameter to the getattr() property.
  2. Handle the getattr() property in the try-except block.

3.1 getattr() property Syntax

Following is the syntax of the getattr() property.


# Syntax of getattr()
getattr(object,attribute,default_message)

3.2 getattr() property Parameters

  • First parameter is the instance of the class (object).
  • Second parameter is the attribute name.
  • Last parameter is used to specify the default message which is a string. It can be optional.

3.3 getattr() Examples

Example 1: Let’s return the attribute value that already exists in the class.

Here, we are returning the ‘name‘ attribute value. ‘AP‘ is the value assigned to it. So it is returned.


# Create class named State
class State:
  name = 'AP'
  population = 23000
  country="India"

# Object for the State
data1 = State()

# Return name using getattr()
getattr(data1,'name')

# Output:
# AP

Example 2: Let’s try to return the attribute value that doesn’t exist in the class.


# Try to return city using getattr() without default message
print(getattr(data1,'city'))

Since the city attribute doesn’t exist in the class, it returns the following error.

Handling AttributeError:

  1. By specifying the default message: We can handle the error by displaying the default message.

class State:
  name = 'AP'
  population = 23000
  country="India"

# Object for the State
data1 = State()

# Try to return city using getattr() with default message
print(getattr(data1,'city','City Not exists'))

# Output:
# City Not exists

You can see that AttributeError is not returned. The default message is displayed.

2. Using try-except block


class State:
  name = 'AP'
  population = 23000
  country="India"

# Object for the State
data1 = State()

# Try to return city using getattr()
try:
    print(getattr(data1,'city'))
except:
    print("city attribute doesn't exist!")

# Output:
# city attribute doesn't exist!

Here, we specified getattr() property in the try block, As the ‘city’ attribute doesn’t exists, except block is executed and the message is displayed.

4. delattr() property

The delattr() property deletes the attribute from the class. It takes class and attribute as parameters.

If the attribute doesn’t exist, It will return AttributeError. We can handle this scenario using a try-except block.

4.1 delattr() property Syntax

Let’s look at the syntax that uses delattr() property.


# Syntax of delattr()
delattr(class,attribute)

4.2 delattr() property Parameters

  • First parameter is the class name.
  • Second parameter is the attribute name to be deleted.

4.3 Examples

Example 1: Let’s delete the ‘population‘ attribute from the class ‘State’ using delattr().


#Create class State
class State:
  name = 'AP'
  population = 23000
  country="India"

# Object for the State
data1 = State()

print("Actual Data:")
print("State Name: ",data1.name," ->" ,"Population: ",data1.population," ->" ,"Country: ",data1.country)

# Delete population attribute using delattr()
delattr(State,'population')

print("Final Data:")
print("State Name: ",data1.name," ->" ,"Country: ",data1.country)

# Output:
# Actual Data:
# State Name:  AP  -> Population:  23000  -> Country:  India
# Final Data:
# State Name:  AP  -> Country:  India

The ‘population‘ attribute exists in the class and it is deleted.

Example 2: Let’s try to delete the attribute – ‘city’ that doesn’t exists in the class.


class State:
  name = 'AP'
  population = 23000
  country="India"

# Object for the State
data1 = State()

# Try to return city using getattr() without default message
print(delattr(data1,'city'))

This yields the following error.

Handling AttributeError:

By specifying the delattr() inside the try block.


class State:
  name = 'AP'
  population = 23000
  country="India"

# Object for the State
data1 = State()

# try to delete city attribute using delattr()
try:
    delattr(State,'city')
except:
  print("city attribute doesn't exist!")

5. hasattr() property

The hasattr() property is used to check whether a particular attribute exists in the class or not. If an attribute exists, True is returned. Otherwise False is returned.

5.1 hasattr() property Syntax

Following is the syntax of the delattr() property.


# Syntax of hasattr()
hasattr(class,attribute)

5.2 delattr() property Parameters

  • First parameter is the class name.
  • Second parameter is the attribute name to be checked.

5.3 hasattr() Examples

Example 1: Let’s have a class with three attributes. Check whether the attribute – ‘name’ exists or not.


# Create class State
class State:
  name = 'AP'
  population = 23000
  country="India"

# Object for the State
data1 = State()

print("Actual Data:")
print("State Name: ",data1.name," ->" ,"Population: ",data1.population," ->" ,"Country: ",data1.country)

# Does name attribute exists?
hasattr(State, 'name')

# Output:
# Actual Data:
# State Name:  AP  -> Population:  23000  -> Country:  India
# True

‘name’ attribute exists in the class – ‘State’. So True is returned.

Example 2: Let’s have a class with three attributes. Check whether the attribute – ‘name’ exists or not.


class State:
  name = 'AP'
  population = 23000
  country="India"

# Object for the State
data1 = State()

print("Actual Data:")
print("State Name: ",data1.name," ->" ,"Population: ",data1.population," ->" ,"Country: ",data1.country)

# Does city attribute exists?
hasattr(State, 'city')

# Output:
# Actual Data:
# State Name:  AP  -> Population:  23000  -> Country:  India
# False

The ‘city‘ attribute doesn’t exist in the class ‘State‘. So False is returned.

6. Conclusion

We have seen how to set the attribute of a class using the setattr() property, it can also be possible to update the existing value with this property. To return the value of the attribute use the getattr() property. delattr() property is used to delete attributes. hasattr() is used to check whether the attribute exists in the class or not.