The Wayback Machine - https://web.archive.org/web/20241108023510/https://www.geeksforgeeks.org/difference-between-attributes-and-properties-in-python/
Open In App

Difference between attributes and properties in Python

Last Updated : 20 Aug, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Class Attribute: Class Attributes are unique to each class. Each instance of the class will have this attribute. 

Example:

Python3




# declare a class
class Employee: 
    
    # class attribute
    count = 0      
        
    # define a method
    def increase(self): 
        Employee.count += 1
    
# create an Employee 
# class object
a1 = Employee() 
  
# calling object's method
a1.increase() 
  
# print value of class attribute
print(a1.count) 
     
a2 = Employee() 
  
a2.increase() 
  
print(a2.count) 
    
print(Employee.count)


Output:

1
2
2

In the above example, count variable is a class attribute.

Instance Attribute: Instance Attributes are unique to each instance, (an instance is another name for an object). Every object/instance has its own attribute and can be changed without affecting other instances.

Example:

Python3




# create a class
class Employee: 
    
    # constructor
    def __init__(self): 
        
        # instance attribute
        self.name = 'Gfg'
        self.salary = 4000
    
    # define a method
    def show(self): 
        print(self.name) 
        print(self.salary) 
  
# create an object of 
# Employee class
x = Employee()
  
# method calling
x.show()


Output:

Gfg
4000

Now, Let’s see an example on properties:

1) Create Properties of a class using property() function: 

Syntax: property(fget, fset, fdel, doc)

Example:

Python3




# create a class
class gfg: 
    
    # constructor
    def __init__(self, value): 
        self._value = value 
            
    # getting the values 
    def getter(self): 
        print('Getting value') 
        return self._value 
            
    # setting the values 
    def setter(self, value): 
        print('Setting value to ' + value) 
        self._value = value 
            
    # deleting the values 
    def deleter(self): 
        print('Deleting value') 
        del self._value 
      
    # create a properties
    value = property(getter, setter, deleter, ) 
    
# create a gfg class object
x = gfg('Happy Coding!') 
print(x.value) 
    
x.value = 'Hey Coder!'
    
# deleting the value
del x.value


Output:

Getting value
Happy Coding!
Setting value to Hey Coder!
Deleting value
 

2) Create Properties of a class Using @property decorator:

We can apply the property function by using @property decorator. This is one of the built-in decorators. A decorator is simply a function that takes another function as an argument and adding to its behavior by wrapping it.

Example:

Python3




# create a class
class byDeco: 
    
   # constructor
    def __init__(self, value): 
        self._value = value 
            
    # getting the values
    @property              
    def value(self): 
        print('Getting value') 
        return self._value 
            
    # setting the values     
    @value.setter 
    def value(self, value): 
        print('Setting value to ' + value) 
        self._value = value 
            
    # deleting the values 
    @value.deleter 
    def value(self): 
        print('Deleting value') 
        del self._value 
    
    
# create an object of class
x = byDeco('happy Coding') 
print(x.value) 
    
x.value = 'Hey Coder!'
    
# deleting the value
del x.value


Output:

Getting value
happy Coding
Setting value to Hey Coder!
Deleting value

Table of difference between Attribute V/s Property

Attribute

Property

Attributes are described by data variables for example like name, age, height etc. Properties are special kind of attributes.

Two types of attributes:

  • Class attribute
  • Instance attribute
It has getter, setter and delete methods like __get__, __set__ and __delete__ methods.
Class attributes are defined in the class body parts usually at the top.  We can define getters, setters, and delete methods with the property() function.
Instance attribute are defined in the class body using self keyword usually it the __init__() method. If we just want to the read property, there is also a @property decorator which you can add above your method.


Similar Reads

Should I Use "Public" Attributes or "Public" Properties in Python?
In Python, deciding whether to use "public" attributes or "public" properties can significantly impact the design and maintainability of your code. Public attributes are straightforward to use, while properties offer more control and encapsulation. Understanding the differences between these two approaches and knowing when to use each can help you
4 min read
Accessing Attributes and Methods in Python
Attributes of a class are function objects that define corresponding methods of its instances. They are used to implement access controls of the classes. Attributes of a class can also be accessed using the following built-in methods and functions : getattr() - This function is used to access the attribute of object. hasattr() - This function is us
3 min read
Class and Instance Attributes in Python
Class attributes: Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility. [GFGTABS] Python # Write Python code here class sampleclass: count = 0 # class attribute def increase(self): sampleclass.count += 1 # Calling increase() on an
2 min read
Filtering Images based on size attributes in Python
Prerequisite : PIL_working-images-python Given an Image directory, our program will create a new image directory based on given threshold size. A simple Python3 function that inputs the path of python file, the threshold width in pixels and the threshold height in pixels, searches all the images present in that only directory and creates a new dire
2 min read
Python | PIL Attributes
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. Attributes: Attribute defines the various property of an object, element or file. In the image, attribute refers to the size, filename, format or mode, etc. of the image. Image used is: Instances of the Image class have the following attributes:
2 min read
Python PIL Attributes | Image.width Method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images. The Image class have th
1 min read
Python PIL Attributes | Image.height method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images. The Image class have th
1 min read
How to Get a List of Class Attributes in Python?
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can
4 min read
Dynamic Attributes in Python
Dynamic attributes in Python are terminologies for attributes that are defined at runtime, after creating the objects or instances. In Python we call all functions, methods also as an object. So you can define a dynamic instance attribute for nearly anything in Python. Consider the below example for better understanding about the topic. Example 1:
2 min read
Dataframe Attributes in Python Pandas
In this article, we will discuss the different attributes of a dataframe. Attributes are the properties of a DataFrame that can be used to fetch data or any information related to a particular dataframe. The syntax of writing an attribute is: DataFrame_name.attribute These are the attributes of the dataframe: indexcolumnsaxesdtypessizeshapendimempt
11 min read
Sort a list of objects by multiple attributes in Python
In this article, we are going to learn how to sort a list by multiple attributes with Python. Introduction Python is a dynamically typed language that offers numerous data types, such as list, tuple, set, dictionary, etc. and sorting is the most commonly used operation on any data structures such as list in Python. To perform this we can use the so
7 min read
How to Add Attributes in Python Metaclass?
This article explains what a metaclass is in the Python programming language and how to add attributes to a Python metaclass. First, let's understand what a metaclass is. This is a reasonably advanced Python topic and the following prerequisites are expected You have a good grasp of Python OOP Concepts.You are familiar with Python programming langu
4 min read
How to Change Class Attributes in Python
In Python, editing class attributes involves modifying the characteristics or properties associated with a class. Class attributes are shared by all instances of the class and play an important role in defining the behavior and state of objects within the class. In this article, we will explore different approaches through which we can edit class a
3 min read
Python Attributes: Class Vs. Instance Explained
In Python, attributes are properties associated with objects. They can be variables or methods that are defined within a class or an instance of a class. Understanding the difference between class and instance attributes is fundamental in object-oriented programming. Here's an explanation: Python Attributes: Class Vs. Instance ExplainedBelow, is th
4 min read
How to Print Object Attributes in Python
In Python, objects are the cornerstone of its object-oriented programming paradigm. An object is an instance of a class, and it encapsulates both data (attributes) and behaviors (methods). Understanding how to access and print the attributes of an object is fundamental for debugging, inspecting, and utilizing these objects effectively. This article
2 min read
Name and Rename Attributes in Pandas
In the world of data science and analysis, the Pandas library in Python plays a crucial role that cannot be neglected when we talk about data manipulation and exploration. Data frames and series are the core structures of the Pandas library. Data frames are used to describe 2-dimensional data structures similar to a spreadsheet or SQL table, on the
4 min read
Attributes in C#
Attributes are used in C# to convey declarative information or metadata about various code elements such as methods, assemblies, properties, types, etc. Attributes are added to the code by using a declarative tag that is placed using square brackets ([ ]) on top of the required code element. There are two types of Attributes implementations provide
4 min read
wxPython - Get Default Attributes of StaticText
In this article, we are going to learn how can we get different attributes of StaticText like background, foreground colors, and fonts. We use GetClassDefaultAttributes() function to get an object of wx.VisualAttributes. It may or may not take variant as an argument. Syntax: wx.StaticText.GetClassDefaultAttributes() or wx.StaticText.GetClassDefault
1 min read
wxPython | Get default attributes of Radio Box
In this article we are going to learn about GetClassDefaultAttributes() function associated with wx.RadioBox class of wxPython. GetClassDefaultAttributes() function is used to return wx.VisualAttributes object for properties like background color, foreground color and font associated with Radio box. It takes variant as arguments. Syntax: wx.RadioBo
1 min read
wxPython - Get visual attributes of static box
In this article we are going to learn how can we get wx.VisualAttributes associated with Static Box. In order to do that we will use static GetClassDefaultAttributes() function. GetClassDefaultAttributes() function is used to return wx.VisualAttributes object for properties like background colour, foreground colour and font. Syntax: wx.StaticBox.Ge
1 min read
PYGLET – Getting all the Style attributes of Formatted Document
In this article we will see how we can get all the style of the formatted document in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be
2 min read
How to Handle duplicate attributes in BeautifulSoup ?
Sometimes while obtaining the information, are you facing any issue in handling the information received from duplicate attributes of the same tags? If YES, then read the article and clear all your doubts. Once you have created the list to store the items, write the given below code. Syntax: list=soup.find_all("#Widget Name", {"id":"#Id name of wid
2 min read
Can "list_display" in a Django ModelAdmin Display Attributes of ForeignKey Fields?
Django's admin interface is a powerful tool for managing application data. One of the common requirements while using Django admin is to customize the way data is displayed. The list_display attribute in Django's ModelAdmin is particularly useful for this purpose, allowing developers to specify which fields should be displayed in the list view of t
3 min read
Python | Clustering, Connectivity and other Graph properties using Networkx
Triadic Closure for a Graph is the tendency for nodes who has a common neighbour to have an edge between them. In case more edges are added in the Graph, these are the edges that tend to get formed. For example in the following Graph : The edges that are most likely to be formed next are (B, F), (C, D), (F, H), and (D, H) because these pairs share
6 min read
Working with Page Orientations and Pagination Properties - Python .docx Module
Prerequisite: Working with .docx module Word documents contain formatted text wrapped within three object levels. The Lowest level- run objects, middle level- paragraph objects, and highest level- document object. So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the pytho
4 min read
Matplotlib.axes.Axes.properties() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. matplotlib.axes.Axes.properties() Function The Axe
6 min read
Matplotlib.artist.Artist.properties() in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Artist class contains Abstract base class for objects that render into a FigureCanvas. All visible elements in a figure are subclasses of Artist. matplotlib.artist.Artist.properties() method The properties() method in artist module of matplotlib li
7 min read
Matplotlib.axis.Tick.properties() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. Matplotlib.axis.Tick.properties() Function The Tick.properties() function in axis module of matplotlib library is used to get a d
2 min read
Matplotlib.axis.Axis.properties() function in Python
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. matplotlib.axis.Axis.properties() Function The Axis.properties() function in axis module of matplotlib library is used to get the
7 min read
Read Only Properties in Python
Prerequisites: Python Classes and Objects A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. To put it in simple words, let us assume a class Student, a
2 min read
Practice Tags :
three90RightbarBannerImg