How do object and class attributes work in Python ?

Class that defines a square

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

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

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

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
>>> 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'

What are the differences between class and instance attributes ?

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

  • Advantages:
  • Drawbacks:

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

>>> 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})

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Summary of RESTfull API

Using Kubernetes for Simulation Infrastructure Automation

Site Reliability Engineering in Enterprise-Scale Organizations

11 Beginner Tips for Learning Python Programming

Declarative Approach to Chaos Hypothesis using Litmus Probes

Pioneering in an Unconventional way — Scoobiverse Launch

How to use prebuilt Rubies to cut your Rails server’s provisioning time by more than 60%

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rémi Marçais

Rémi Marçais

More from Medium

Everything is an object in Python!!

7 Best Tips For Choosing The Best Python Programming Help

A Brief and Beginner Friendly Introduction to Git

Coding for Fun!!!