Class versus Instance attributes in Object-Oriented Programming

Van Phan
2 min readMay 29, 2019

--

Object-Oriented Programming brief definition?

Before we jump to the definition of object-oriented programming, we need to understand what is an object in Python. Almost everything in Python is an object. An object is the center of object-oriented programming. It includes the data and its procedures to control the data structure.

Object-oriented programming (OOP) is a programming model or paradigm which creates a data structure that organizes your data and functions to an individual object.

Class Attributes

A class attribute is a data or a variable that is belonged or attached to the class itself. For instance, new is a class “brandattribute in the below code.

class brand:
new = "hello"

By using brand.new, you can access the class attribute value. And the output is:

hello

You can create a private class attribute by adding “__” before the name of the attribute.

How to create it?

You can create a class attribute by declaring in the class body (often at the top of the class body).

Instance Attributes

An instance copies the actual value of the class, and you can create multiple instances with many copies of the class value.

An instance attribute is an attribute that is belonged to a specific instance of the class.

class A:
def __init__(self, f=2):
self.foo = foo

or

class B:
new = "Hello"
old = B()
old.new = "Goodbye"
print(old.new)

Output:

Goodbye

How to create it?

You can create an instance attribute by using the syntax name.class_attribute to access them outside of the class or you can use the __init__ method to initialize the instance attribute inside the class.

The differences between class and instance attributes

The class attribute is owned by the class itself and can share its value with every instance inside it.

The instance attribute is a unique attribute that is owned by a specific instance and can be accessed inside that instance.

The pros and cons of class and instance attributes

Class attribute:

Pros:

  • Use to store data that can be shared across all instances.
  • all instances can access data from the class attribute

Cons:

  • If you change the data of the class attribute, it’s gonna effect and change the value of all instances.

Instance attribute:

Pros:

  • You can change or remove the value easily inside the instance without affecting other instances.

Cons:

  • It is hard to change the value of multiple instances attributes to every instance.

Use __dict__ method over object and class attribute

The __dict__ method helps print out the internal dictionary of attributes for the specific instance. The __dict__ contains only the user-provided attributes.

example.__dict__
output:
{'current': '1', 'temp': <function tempFunction at 0x7f77951a95f0}

--

--