×

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

Difference between Python and CPP

Difference between Python and C++ We all know that both C++ and Python are two of the most popular programming languages. Both C++ and Python shares some basic similarities such as...

6 minutes read.

Change Data Type in Python

Python is a dynamic language where it is not always required to consider every variable type. Python supports a wide range of data types, but There are mainly six data...

3 minutes read.

Best resources to learn Numpy and Pandas in python

In this tutorial, we will discuss the different resources where we can learn about NumPy and Pandas libraries of Python in a more efficient way. NumPy NumPy, a Python library used for...

4 minutes read.

BOTTLE Python Web Framework

The Bottle is a lightweight WSGI micro web framework for python. It acts like a thin wrapper around a web server where it is distributed as a single file module...

4 minutes read.

Python Matrix Multiplication

One of the most fundamental mathematical structures, matrices are used often in many disciplines, including mathematics, physics, engineering, computer science, etc. For example, matrices and associated operations (multiplication and addition) are...

8 minutes read.

chr() and ord() Functions in Python

Python language contains many built-in functions which we use for many programs to work efficiently. The chr() and ord() are a few built-in functions in Python that are used for...

4 minutes read.

Python Dictionary popitem() method

Python Dictionary popitem() method The dictionary.popitem() method in Python removes the item that was last inserted into the dictionary. Syntax dictionary.popitem() Parameter NA Return This method returns an arbitrary element (key, value) pair from the given dictionary...

1 minute read.

How to open a file in python

Opening a File in Python Python is a user-friendly programming language that makes almost every concept easy. It provides many inbuilt functions in its libraries to work with files. Using these...

6 minutes read.

Python Set intersection_update() method

Python Set intersection_update() method The set.intersection_update() method in Python removes the items that is not present in both sets. It is different from the set.intersection() method, because the intersection()method returns a new set, with only  the common elements...

2 minutes read.

Python Pass Statement

The pass statement is a null statement. The difference between pass and comment is that comment is ignored by the interpreter, whereas pass is not. The pass statement is typically used...

3 minutes read.

Python program to check if two strings are anagram or not

Python program to check if two strings are anagram or not Problem: This is a python program that takes two strings and checks if given strings are anagram or not. Examples: Input: string1...

1 minute read.

Sort Dictionary in Python

Dictionaries In Python, a dictionary is an unordered collection or set of data types that enable of store data in an unordered key-value/pair. The key is stored alongside with value. Dictionary contains key:...

4 minutes read.

Struct Module in Python

What is a structure in Python? An entity that holds data in form of a structure is called a data structure. In Python, the data structure includes tuples, lists, dictionaries, and...

4 minutes read.

Tuple in Python

Tuples Tuples are the same as the list but as we know that lists are mutable means we can change the data from it. In the tuple we cannot change the...

6 minutes read.

How to comment multiple lines in python?

How to comment multiple lines in python There are two qualities that come up with every good and successful programmer- i) Indenting the code ii) Using comments in the code Let us see how...

4 minutes read.

Python String islower() method

Python String islower() method The string.islower() method returns a boolean value true if all cased characters in the string are lowercase and for  any other value is returns false otherwise. Syntax string.islower() Parameter NA Return This...

1 minute read.

Python Errors and exceptions

Exceptions and errors are the obstacles a programmer constantly faces while writing a program. Firstly, we need to understand what are errors and exceptions and the difference between these two...

6 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

Rank Based Percentile GUI Calculator using Tkinter in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

3 minutes read.

Multiprocessing in python

The word multiprocessing is used to compute the operation in which more than two processors run simultaneously with more than one central processor. The computer's performance increases gradually. Multiprocessing is...

6 minutes read.