×

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

JWT Decode Python

Python's PyJWT package makes it possible to encrypt and decrypt JSON Web Tokens (JWT). JWT is a public, recognized global benchmark for safely expressing demands between two parties (RFC 7519). JSON...

7 minutes read.

Python len() function

Python len() function The len() function in Python  returns the number of items in an object. Syntax len(s) Parameter s: This parameter represents a sequence (such as a string, bytes, tuple, list, or range) or...

1 minute read.

How to assign values to variables in Python and other languages?

Python makes it simple to construct variables. The value to be stored in the variable should then be written after a suitable name for the variable and the equality sign....

3 minutes read.

How to declare array in python

How to declare array in python? Arrays are a great way of storing our numeric values into a variable in continuous locations. For declaring an array in C language, we used...

4 minutes read.

Python Tutorial

Python tutorial is a widely used programming language which helps beginners and professionals to understand the basics of Python programming easily. Python is a high-level, easy, interpreted, general-purpose, and dynamic programming...

19 minutes read.

Cube Root in Python

In general, the cube is a three-dimensional solid figure that has 6 square faces. It is also called a geometrical shape with six equal faces, eight vertices, and twelve edges....

3 minutes read.

Convert String to Binary in Python

String to binary The strings can be defined as the array of Unicode code characters. Binary Binary is defined as the number system which consists two symbols 0 and 101. It is base-2...

2 minutes read.

Python hash() function

Python hash() function The hash() function in Python returns the hash value of the object (if it has one).  Syntax hash(object) Parameter obj : This parameter represents the object which we need to convert into hash. Return This...

1 minute 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.

How to print in same line in python

How to Print in the Same Line in Python To print in Python, we use the print () function and the syntax of print () goes like this: print (values, sep =...

3 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.

Type casting in Python

Introduction Type Casting is defined as the method of converting the variables/values data type into a certain data type for matching the operation needed to be performed by the users. This...

4 minutes read.

Python System Command

To execute a program in Python, we need to execute some shell commands to run our program on the computer. Python will provide some shell commands in our background to...

3 minutes read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

Method Overloading in Python

Overloading is a capability of a method and operator to behave differently according to the nature of parameters. Overloading is popular because it provides a good number of advantages: Reusability of code.Reduces...

3 minutes read.

iobase Python

All I/O flow classes derive from this conceptual base class. Derived classes will have to execute several of the class's abstract data types. The loop method is supported by all members of...

4 minutes read.

Python Decorator

Python Decorator: A Decorator is an interesting feature of Python that helps the user design patterns and insert a new functionality to an existing object without making any modifications in...

6 minutes read.

Assertion Errors and Attribute Errors in Python

Assertion Error in Python In Python, the assert condition is used to continue the execution if the given statement displays true. If the assert statement displays false, it raises Assertion Error...

3 minutes read.

Idle python download for Windows

Here, we will be discussing how to get the answer to all questions related to installing Python on Windows. What is IDLE? Integrated Development and Learning Environment, or IDLE, is a shorthand....

3 minutes read.

Image to Text in python

Processing out information from an image is a very big task in all the fields of work such as in development and business sector. The process of converting an electronical...

3 minutes read.