×

Attributes in python

In this article, we shall learn about attributes in python. Classes are a mix of data and functions, which in reality mean attributes and methods respectively.

Typically, the body of a class will be a series of function definitions. When functions are defined inside of a class, then they are called methods. Think of the class as owning these methods.

Example:

# let C be a class
class C:
    def fun1():
        print( " This is function 1 " )
    def fun2():
        print( " This is function 2 " )
    def fun3():
        print( " This is function 3 " )
def fun3():
        print( " This is function 3 " )

# fun1, fun2, fun3 and fun4 are methods of class C

Now, objects are created from classes. These objects have attributes, which are just variables stored inside an object. The syntax for accessing and using attributes is the name of the object variable, followed by a dot, followed by the name of the attribute.

SYNTAX of accessing an attribute:

object.attribute

Example:

# let C be a class 
obj = C()
obj.name = “ Rishika “
obj.age = 19
obj.age = obj.age + 1
print( f" The name given to obj is { obj.name } " )
print( f" The updated age of obj is { obj.age } " )

OUTPUT:

The name given to obj is Rishika

The updated age of obj is 20

So, attributes can be of the following types:

Class attributes:

In an object-oriented programming language, when an attribute belongs to a class rather than any object, then it is known as a class attribute.

For example, you created a class called cars. You want to keep track of the number of cars created using your class, then you define a class attribute to the class to keep track of the number of objects created out of it.

Unlike other object-oriented programming languages, we can access class attributes through instance attributes.

Example:

class Car:
    origin = " Vehicle "
    def fun1():
        print( " This is function 1 " )
    def fun2():
        print( " This is function 2 " )
    def fun3():
        print( " This is function 3 " )
# origin is the class attribute of the Car
c = Car()
print( c.origin )

OUTPUT:

Vehicle

Process finished with exit code 0

Instance attributes:

Instance attributes are set when an instance of an object is created. These are defined in the constructors of the given class.

Example:

class Car:
    origin = " Vehicle "
    # defining a constructor
    def __init__(self, color, seats ):
        self.color = color
        self.seats = seats
    def fun1():
        print( " This is function 1 " )
    def fun2():
        print( " This is function 2 " )
    def fun3():
        print( " This is function 3 " )


c1 = Car( " Red ", " 4 " )
c2 = Car( " Blue ", " 7 " )
c1_color = c1.color
c2_color = c2.color
c1_seats = c1.seats
c2_seats = c2.seats
print( f" c1 is { c1_color } in color and has { c1_seats } seats " )
print( f" c2 is { c2_color } in color and has { c2_seats } seats " )

Output:

c1 is Red in color and has 4 seats

 c2 is Blue in color and has 7 seats

Process finished with exit code 0

Private attribute:

Private attributes are declared under the concept of encapsulation. A private attribute, as the name suggests is private to the class, i.e., you can use this attribute inside the class, but if you use it outside the class, it gives you an error. So, you cannot access a private attribute outside a class.

We declare a private attribute by providing two underscore symbols before its name.

SYNTAX:

self.__privateattribute = privateattribute

Example:

class Example:
    def __init__( self, x):
        self.a = 10
        self.b = 20
        self.__c = 30
    def fun1( self ):
        print( f" The private attribute of Example class is { self.__c } " )
e = Example( 25 )
print( e.a )
print( e.b )
print( e.__c)

OUTPUT:

Traceback (most recent call last):

  File "xxx\main.py", line 11, in <module>

    print( e.__c)

AttributeError: 'Example' object has no attribute '__c'

10

20

Process finished with exit code 1

class Example:
    def __init__( self, x):
        self.a = 10
        self.b = 20
        self.__c = 30
    def fun1( self ):
        print( f" The private attribute of Example class is { self.__c } " )
e = Example( 25 )
print( e.a )
print( e.b )
e.fun1()

OUTPUT:

10

20

 The private attribute of the Example class is 30

Process finished with exit code 0


Related Topics

One Liner If-Else Statements in Python

Before learning one liner if else Python, let us first know what Python is. Python is a broadly helpful, object-oriented and dependable language having a large number of utilizations from...

4 minutes read.

Uint8 Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python float()

Python float() class The float() class in Python returns a floating point number constructed from a number or string x. Syntax class float([x]) Parameter x: This parameter represents a number or a string that can be converted...

1 minute read.

PyDev with Python IDE

What is IDE? Integrated Development Environment is the abbreviation of IDE. It is a coding tool that automates code editing, finding errors and testing. IDE combines all the developer tools into...

3 minutes read.

Python program for perfect number

Python program for perfect number Before writing any program for a given problem, we have to understand the problem for which we are creating a solution program. So, let's understand what...

2 minutes read.

*Args and **Kwargs in Python

Let’s know about ** (dual star / asterisk) and * (star / asterisk) are operators in Python. These stars are used in Python for parameters. Args and kwargs are special...

3 minutes read.

Python String index() method

Python String index() method The string.index() method in Python finds the lower index of the first occurrence of the specified value or raise a ValueError if the substring is not found. Syntax index(sub[, start[, end]]) Parameter sub:...

2 minutes read.

Python String rsplit() method

Python String rsplit() method The string.rsplit() method in Python splits a string into a list, starting from the right. If the "max" parameter is not specified, this method will return the...

1 minute read.

Rank Based Percentile GUI Calculator using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With the capabilities...

3 minutes read.

Standard GUI Unit Converter using PyQt5 in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Unit Testing in Python

The process of testing whether a particular unit is working properly or not is called “UNIT TESTING”. A unit test will check small components in your application. The first and...

7 minutes read.

How to create a list in Python?

How to create a list in python Python is known for its versatility and its data structures help us to perform different kinds of operations on various datasets irrespective of their...

4 minutes read.

Sort a dataframe based on a column in Python

Sorting the dataframe based on a column requires pandas which is An open-source library called Python Pandas is described as offering high-performance data processing in Python. For both professionals and...

4 minutes read.

How to check version of Python

How to check version of python The versions of Python come with different kinds of features and functionalities. It is not a herculean task to keep track of the updates these...

3 minutes read.

Python Unit Test Cheat String

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to build an Auto Clicker using Python?

What is an Auto Clicker? An Auto Clicker is software that is used for automating the click of a mouse on any particular element on the computer screen and controlling the...

8 minutes read.

Excel to CSV in Python

Define MS Excel Microsoft Excel is an application provided by the Microsoft corporation which allows us to build graphs to build tables, and it is also used for the macro programming...

4 minutes read.

Application to Search Installed Application using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Python Set difference() Method

Python Set difference() Method The set.difference() method in Python returns the set difference of two sets(A-B). Syntax set.difference(set1) Parameter set- This argument represents a set (minuend) set1- This arguments represents a set(subtrahend) Return This method returns the difference of the two specified...

2 minutes read.

wxPython Panel class

wxPython Panel class The Widgets which is shown in the frame of GUI window such as text box, buttons, static text etc. are put inside the panel class of the wxpython...

2 minutes read.