Class and instance attributes

What can happen if we define a Human like an OOP? -> class Human

What’s a class attribute?

We define the class attribute inside of the class

What’s an instance attribute?

we can see in the example a difference between a class attribute and an instance attribute. When we call an instance attribute, it only affects the specific instance of a class (in the example: x.a)

What are all the ways to create them and what is the Pythonic way of doing it?

  • Class attribute are represented after Class Rectangle: “number_of_instances” and “print_symbol”
  • Instance attribute: We create after the initializer (__init__). It is automatically called when we instantiate the class. We have to include the self parameter so that our initializer has a reference to the new object being instantiated. With this form, any Rectangle object will be able to stores it width and height
"""class Rectangle"""
class Rectangle:
"""Constructor of the empty class Rectangle"""
number_of_instances = 0
print_symbol = '#'
def __init__(self, width=0, height=0):
self.width = width
self.height = height
Rectangle.number_of_instances += 1

Now, let’s handle what is Pythonic:

class Square:
"""Constructor of class Square"""
def __init__(self, size=0):
if not isinstance(size, int):
raise TypeError("size must be an integer")

if size < 0:
raise ValueError("size must be >= 0")

self.__size = size * size
def area(self):
return self.__sizet__width()
class Square:
"""Constructor of class Square"""
def __init__(self, size=0):
self.size = size
def size(self):
return self.__size
def size(self, value):
if not isinstance(value, int):
raise TypeError("size must be an integer")
if value < 0:
raise ValueError("size must be >= 0")
self.__size = value
def area(self):
return self.__size * self.__size

What are the differences between class and instance attributes?

  • A class attributes are shared, so we can say that they can be accessed by all instances of that class. In the next example, we can see that “number_of_instances” and “print_symbol” will be shared to all Rectangles instance of the “class Rectangle”. And the value is the same. We can see that in the next example we use to have a counter of instances of the “class Rectangle” and also define a symbol that we will print the square. These class attributes values will be the same for all instances of the class
Example of class Rectangle Class which has class and instance attributes
  • Instance attributes are owned by each individual instance of the class. We can have a good example in the next image: We can see that each object (Dog1, Dog2, Dog3) have different instance attributes (Breed, Size, Colour and Age values are different for each one)

What are the advantages and drawbacks of each of them?

Advantages and drawbacks of Class Attribute:

  • They store a variable that are shared between all object. We can use it to store data relevant like number of instance of the class or another
  • If we need the same variable with the same value for all the instances of the class, we can choose a Class Attribute
  • One disadvantage is when an object name attribute has the same name as the class variable. They will hide the class variable

Advantages and drawbacks of Instance Attribute:

  • We can create a instance attribute and it will have different values for each object of the class, so it will easy to handle it
  • We can use the pythonic way to access to the properties, getter and setter methods, so we can set an attribute of a specific instance easily
  • You can not update all the instance attribute at the same time like the Class attribute and it is because it is different for each object. They have different uses

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

class Robot:

x = Robot()
y = Robot() = "Marvin"
x.build_year = "1979" = "Caliban"
y.build_year = "1993"
# Output:
{'name': 'Marvin', 'build_year': '1979'}
# Output:
{'name': 'Caliban', 'build_year': '1993'}
class MyClass(object):
class_var = 1

def __init__(self, i_var):
self.i_var = i_var

foo = MyClass(2)
bar = MyClass(3)

print MyClass.__dict__
print foo.__dict__
print bar.__dict__
{'__module__': '__main__', 'class_var': 1, '__dict__': <attribute '__dict__' of 'MyClass' objects>, '__weakref__': <attribute '__weakref__' of 'MyClass' objects>, '__doc__': None, '__init__': <function __init__ at 0x0000000004E55CF8>}
{'i_var': 2}
{'i_var': 3}




Software engineer in progress

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

Recommended from Medium

The Spotify Democratization — Chapter 2

An Intro to TDD using RSpec in Ruby

Python — ETL and yield

4 Basics of Object Oriented Programming.

Download Cricket Exchange MOD APK v21.10.07

OAuth2 implementation with ORY Hydra, Vapor 3 and iOS 12

Managing On premises mailboxes with Intune, MAM, Conditional Access, and where the customer data…

Part 2: An easy way to automatically manage the AWS SG with Terraform and Python…

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
Katherine Soto

Katherine Soto

Software engineer in progress

More from Medium

Un-Cringing An is_even() Function in Python

Kᵗʰ smallest element in an array — with Quicksort variation

Kth smallest element

Everything is object in Python

Tricky things in C++: new and delete operators