How do object and class attributes work in Python ?

How do object and class attributes work in Python ?

Classes and objects are the main aspects of object oriented programming (OOP) and they are very useful in OOP languages such as Python, which is an interpreted general-purpose programming language that was created in 1991 by Guido Van Rossum.

Classes are data type that can be defined by users and which can create objects while objects are instances of class, that is to say a kind of “copy” of a class with particular values. For example, “hello” is a str object, so an instance of the classe str.

What’s a class attribute and how to create it ?

In Python, class attributes are attributes that are shared by all the instances of this class and that can be called by the class or by ist instances. They are owned by the class and defined outside the __init__ method (which is the constructor function). More precisely, class attributes (like attributes in general) refer to the fields and the methods of this class. Fields are variables that belong to an object or a class while methods are functions that belong to a class. To create a class attribute, you can do it this way (We usualy declare it at the top, just below the class header):


class Example
    string = "This is a class attribute"
example_1 = Example()
print(example_1.string)
Output:
This is a class attribute:        

We can see that?example_1?is an instance of the class?Example?and?string?is a class attribute.

If you update a class attribute by doing, for example:

Example.string = "This is an updated class attribute"        

All the instances of the class Examplewill be updated:

example_1.strin

Output:
'This is an updated class attribute'        
No alt text provided for this image

What’s an instance attribute and how to create it ?

Contrary to class attributes, instance attributes are specific attributes to each instance and they are not shared between them. They are usually defined in the __init__ method (that is often the first method that an user defines when he creates a class), wich is called directly after the creation of a new instance :


class Square
    string = "This class defines a square"

    def __init__(self, size, color):
        self.size = size
        self.color = color

A = Square(5, "Blue")
print(A.size)
print(A.color)

Output:
5
Blue:        

Here, we still have the class attribute?string?but we have also the __init__ method that defines two instance attributes called?size?and?color(self refers to the current instance).

More:

An instance attribute can be private (starting with “__”). In this case, it can’t be accessed or updated outside the class:


>>> class Square
...     def __init__(self, size):
...         self.__size = size
...
>>> A = Square(5)
>>> A.size
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Square' object has no attribute 'size'
>>> A.__size
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Square' object has no attribute '__size':        
No alt text provided for this image

What are the differences between class and instance attributes ?

As shown previously, there are several differences between class attributes and instance attributes.


Firstly, class attributes are defined in the class and outside methods (usually at the top of the class, below the class header) while instance attributes are defined inside the constructor (__init__ method). Moreover, class attributes are accessible to all instances of this class wherehas instance ones are accessible only to one instance. And another is that we can access a class attribute via the class name or an instance when you can access an instance attribute via the instance to which this attribute belongs (if the attribute is private, you can’t access it outside the class).

So we’ve seen the differences of class and instace attributes, now let’s see the advantages and drawbacks of each of them.

What are the advantages and drawbacks of class and instance attributes ?

No alt text provided for this image

  • Advantages:


Class attributes:

They are the same between instances, so they can be used for example as counter if we want to count how many instances have been created or deleted.

Instance attributes:

They allow users to not have memory leaks because they are deleted when an instance is deleted and they are easy to get and set (you can see?getters and setters). Moreover, instance attributes can be used by methods (for example, if you want to compute the area of a square of size?sizewith a method called?area?, you will take as argument the instance attribute?size?).

  • Drawbacks:


Class attributes:

All the instances of a class will have the same value so you can only do the same thing with all the instances.

Instance attributes:

They can’t be accessed by other instances so you can’t keep a track of an instance value.

How does Python deal with the object and class attributes using the?__dict__??

To finish, if you want to check all class attributes, instance attributes and values, you can use the __dict__ method, that displays a dictionary containing all of these informations as shown below:


>>> class Square

...     string = "I'm a square !"

...     def __init__(self, size, color):

...         self.size = size

...         self.color = color

...

>>> A = Square(5, "Blue")

>>> A.__dict__

{'size': 5, 'color': 'Blue'}

>>> Square.__dict__mappingproxy({'__module__': '__main__', 'string': "I'm a square !", '__init__': <function Square.__init__ at 0x7f56497df670>, '__dict__': <attribute '__dict__' of 'Square' objects>, '__weakref__': <attribute '__weakref__' of 'Square' objects>, '__doc__': None})

        

You’ve reached the end of this post, I hope you enjoyed it ! Thanks for reading and enjoy coding !

No alt text provided for this image

要查看或添加评论,请登录

Thato Khosa的更多文章

  • STEM: Full Stack Web Development

    STEM: Full Stack Web Development

    I’m sure you’ve heard how important STEM is. You’ve also probably heard that people with STEM careers typically do…

  • Hack day: Mastermind challenge

    Hack day: Mastermind challenge

    As a representation of the Medellin campus and the only team, we wanted to face this challenge using C language. To…

  • What is IoT?

    What is IoT?

    What is the Internet of Things (IoT)? In the simplest terms, the Internet of Things (IoT) represents all computing…

  • How SQL Database Engine Work

    How SQL Database Engine Work

    What is a SQL Engine? A typical SQL server database engine configuration includes a storage engine and the query…

  • The concept of recursion

    The concept of recursion

    Good day in this blog we are going to explain the concept of recursion. Well, recursion is a method where the solution…

  • Python — Everything is object

    Python — Everything is object

    We are creating an object of type int. identifiers x and y points to the same object.

  • Differences between static and dynamic libraries

    Differences between static and dynamic libraries

    020 is ending and I couldn't let pass the opportunity to write another article and at this time, and continuing my last…

  • what happens when you type ls -l *.c and hit Enter in a shell?

    what happens when you type ls -l *.c and hit Enter in a shell?

    What happens when you type ls -l *.c in the shell? Hello friends, today you will know what actually happens when you…

  • How integers are stored in memory using two’s complement

    How integers are stored in memory using two’s complement

    An integer is a number with no fractional part; it can be positive, negative or zero. In ordinary usage, one uses a…

  • The C preprocessor's Worst abuse - (IOCCC winner, 1986)

    The C preprocessor's Worst abuse - (IOCCC winner, 1986)

    #include #include unistd.

社区洞察