Difference Between Property And Attribute | Python

If you have adopted another object-oriented programming language effectively, you probably must have realized that the terms- attributes and properties are typically utilized equivalently. Indeed, even in typical English use of the words “attributes” and “property” can be utilized as equivalents.

But when it comes to Python, properties and attributes are two different things. So, without further ado, let’s learn about them.

πŸ”‘ Difference Between a Property And an Attribute in Python

πŸ’‘ You can think of properties as special kind of attributes that provide getter, setter and deleter functionality to an attribute.

Let’s have a look at the following example to understand the difference between the two:

class Finxter:
    # This is an attribute
    def __init__(self,n):
        print("---Attribute---")
        self.name = n
        print("Welcome ", self.name,'\n')

    @property
    def foo(self):
        print("---Getter Method---")
        return self.name

    @foo.setter
    def foo(self,name):
        print("---Setter Method---")
        print("Setting Name as ",name,'\n')
        self.name= name

    @foo.deleter
    def foo(self):
        print("---Deleter Method---")
        del self.name


obj = Finxter('Finxter')
obj.foo = 'Chris'
print("Welcome", obj.foo,'\n')
del obj.foo

Output:

---Attribute---
Welcome  Finxter 

---Setter Method---
Setting Name as  Chris 

---Getter Method---
Welcome Chris 

---Deleter Method---

Explanation:

  • Initially, the __init__ method which is an instance attribute gets invoked. Thus, the output is Welcome Finxter.
  • Python, then comes across the @property decorator. Thus, the getter, setter and deleter methods are executed one by one after that.
PropertyAttribute
β—ˆ A property gives you control over its getter, setter and delete methods, i.e., __get__, __set__ and __delete__.β—ˆ With an attribute you cannot work with the __get__, __set__ and __delete__ methods.
β—ˆ A property can be considered as a special kind of attribute.β—ˆ Attributes can be described with the help of variables like name, age, height etc.
It can be of the following types:-
1. class attributes
2. instance attributes

Let us dive deep into attributes and properties to have a better grip on them.

πŸ’ŽAttributes in Python

In Python, attributes can be of the following types:

  • Class attributes
  • Instance attributes

πŸ“Œ Class Attributes in Python

  • In Python, class attributes are the attributes created inside a class definition and belong to the class itself.
  • Class attributes are shared between all other objects of the same class.

Example:

class Job:
    # class attribute
    exp = 0

    def foo(self):
        Job.exp += 1
        return Job.exp


# Creating object for the class
obj_a = Job()
obj_b = Job()

# class attribute 'experience' is shared by all objects of the class
print("Name: Rashi \t Experience: ", obj_a.foo(), "Year")
print("Name: Shubham \t Experience: ", obj_b.foo(), "Years")

Output:

Name: Rashi 	 Experience:  1 Year
Name: Shubham 	 Experience:  2 Years

Explanation:

In the above program, the class attribute exp is shared by all objects of the class ‘Job‘. Thus, it gets incremented by 1, every time a new instance invokes it.

Note: Class attributes are defined outside the __init__ constructor.

πŸ“Œ Instance Attributes in Python

An object is nothing but an instance of a class in Python. While a class can be considered as a blueprint for which objects can be created.

Instance attributes are unique to each instance in Python. This means, every instance attribute exists independently within the scope of its object and can be changed without influencing other instances.

Example:

# Creating a class
class student:
    def __init__(s):
        # Creating a constructor
        s.name = "Harry Potter"
        s.age = "19"
    # These are instance attributes

    # Defining a method
    def display(s):
        # Printing the details
        print("Student name-", s.name)
        print("Student age-", s.age)


# Creating object st for the student class
st = student()

# Calling the method
st.display()

Output:

Student name- Harry Potter
Student age- 19

Recommended Video Tutorial on AttributesπŸ‘‡

source: https://blog.finxter.com/python-attributes/

πŸ“œ Property in Python

To understand what are properties in Python, let us have a look at the following example:

# Creating a class
class Rectangle(object):
    # Defining a method
    def __init__(self, length, width):
        self.length = length
        self.width = width
        self.area = self.length*self.width


# instantiation
rect = Rectangle(5, 4)
print('Length = {}'.format(rect.length))
print('Width = {}'.format(rect.width))
print('Area = {}'.format(rect.area))

print()
# Changing the length and breadth of rectangle
rect.length = 6
rect.width = 8

print('Length = {}'.format(rect.length))
print('Width = {}'.format(rect.width))
print('Area = {}'.format(rect.area))

Output:

Length = 5
Width = 4
Area = 20

Length = 6
Width = 8
Area = 20
  • In the above example, we notice that the area of the rectangle is 20 when the length and width are 5 and 4 respectively. But the area of the rectangle remains the same (20) even after changing the values of length and width to 6 and 8 respectively.
  • Hence, we to ensure that Python computes the values properly we need to use @property decorator.
    • @property is an inbuilt decorator in Python that allows you to access the getter and setter methods with ease.

Let’s have a look at the solution to our problem.

Solution

class Rectangle(object):
    # Defining a method
    def __init__(self, length, width):
        self.length = length
        self.width = width

    # Using property to calculate area of rectangle
    @property
    def area(self):
        return self.length * self.width


rect = Rectangle(5, 4)
print('Length = {}'.format(rect.length))
print('Width = {}'.format(rect.width))
print('Area = {}'.format(rect.area))

print()
# Changing the length and breadth of rectangle
rect.length = 6
rect.width = 8

print('Length = {}'.format(rect.length))
print('Width = {}'.format(rect.width))
print('Area = {}'.format(rect.area))

Output:

Length = 5
Width = 4
Area = 20

Length = 6
Width = 8
Area = 48

Conclusion

Thus, in this article you learned the major differences between an Attribute and a Property in Python. I hope it helped you to understand-

  • “what are the different types of attributes in Python?”
  • “what are properties in Python”?

Please subscribe and stay tuned for more interesting tutorials. Happy learning!πŸ“š 

Author: SHUBHAM SAYON
Co-author: RASHI AGARWAL

Python One-Liners

Python One-Liners will teach you how to read and write β€œone-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

Get your copy ofΒ Python One-Liners here.