×

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

Python Data Structures

Python Data Structures: Python is a programming language used worldwide for various fields such as building dynamic websites, artificial intelligence and many more. However, there is data that plays a...

18 minutes read.

Python | a += b is not always a = a + b

a += b in Python doesn't always behave the same way as a = a + b; the same operands can produce different outcomes depending on the circumstances. But we...

3 minutes read.

Python Boolean

In this article, you will learn the boolean variables in python, bool() function in python, and bool operators with examples, Boolean Objects in Python. There are the only two possible values...

6 minutes read.

Features of Python

Python is a powerful, easy to learn, popular programming language. It has effective data structures and its elegant syntax makes it user-friendly language. Below are the key features of Python: 1. Python...

4 minutes read.

Flutter with tensor flow in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

3 minutes read.

Enumerate() Function in Python

The enumerate() function in Python is used to convert a data collection object into an enumerate object. It returns an object that contains a counter as a key for each...

3 minutes read.

Python issubclass() Function

Python issubclass() Function The issubclass() function in Python returns a boolean value ‘True’ if the given object is a subclass of classinfo, else it returns False. Syntax issubclass(class, classinfo) Parameter class: It is a required parameter which represents a tuple...

1 minute read.

Binary Search Visualization using Pygame in Python

A calculation like Binary Search is seen effectively by picturing. Here in this tutorial, a function that pictures the Binary Search Algorithm is carried out. The Graphical User’s Interface (GUI)...

15 minutes read.

Python Sys Stdout

Python Programming Language: 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...

3 minutes read.

Create the First GUI Application using PyQt5 in Python

GUI: A graphical user interface, or GUI, is present on most personal computers. It provides a simple experience for individuals with various computing skill levels. GUI apps may take more resources...

3 minutes read.

Cx_Oracle Python with Example

Python Programming Language: 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...

6 minutes read.

Python enumerate() function

Python enumerate() function The enumerate() function in Python takes a collection (e.g. a tuple) and returns it as an enumerate object. Syntax: enumerate(iterable, start=0) Parameter Iterable:  This parameter represents an iterable object start:    This parameter represents a number defining...

1 minute read.

Python String find() method

Python String find() method The string.find() method in Python finds the first occurrence of the specified value and returns the lowest index in the string if the substring sub is found else it...

2 minutes read.

Nested Tuple in Python

If you are a Python learner, this page contains all the information that helps you know about nested tuple and how to access it in python. What is a Tuple? Multiple items...

4 minutes read.

Selection Sort Using Python

Selection sort is a type of sorting algorithm which is based on sorting elements in increasing order or ascending order through comparison. This sorting technique does not take extra space...

3 minutes read.

Matrix List Comprehension in Python

Introduction One of Python's most beautiful features is list comprehension. Iterating over an iterable object to create lists is a clever and succinct method. Nested List or matrix list Comprehensions, which...

6 minutes read.

NSE Tools In Python

About NSE NSE (National Stock Exchange) of India Limited is the advanced stock exchange of India. It is located in Mumbai, Maharastra and It was organized in 1992. It was...

2 minutes read.

Get index of element in array in python

Index : Index is a number where the element is located in the given list. In other words it is the position of the element in the list. Index can also...

4 minutes read.

Difference between Sort and Sorted in Python

If you new to Python, it must be confusing the distinction between the Sort and Sorted functions. However, it is important to understand the differences in order to use them...

5 minutes read.

An Introduction to Mocking in Python

Python Mocking is a testing library. It enables you to substitute portions of your system under test with fake(mock) objects and make assertions about how they were utilized.  The test is...

3 minutes read.