Class and Instance Attributes and their Methods in Python

RuthRuth
4 min read

One of the difficult concepts I had trouble understanding was the differences between both class and instance attributes and their methods, and how and when to use each one. Class methods are useful in certain situations so for the most part instance methods and attributes are more commonly used. First we are going to talk about the difference between what class methods and attributes and instance methods and attributes, what they are and their syntax. We will then talk about when class methods and attributes are useful.

Class Attributes and Methods

A class attribute is a variable created for the class. In python it'll look something like this:

class Book:
    #this a class attribute
    all = {}
    ##############
    def __init__():
        pass

A class method is a method you can call on the class, but in order for python to know that you want a particular method to be a class you use the @classmethod decorator.

class Book:
    #this a class attribute
    all = {}
    def __init__():
        pass
######## Added Code ########
    #This is a class method 
    @classmethod
    def create(cls, title):
        pass
###########################

Instance Attributes and Methods

Instance attributes are variables that the instance has and are set in the __init__ constructor.

class Book:
    all = {}
######## Added Code ########
    def __init__(self, title):
        #these are the instance attribute
        self.id = None
        self.title = title
###########################  
    #This is a class method 
    @classmethod
    def create(cls, title):
        pass

Instance methods are used on the instances of the class.

class Book:
    all = {}
    def __init__(self, title):
    #these are the instance attribute
    self.id = None
    self.title = title
######## Added Code ########
    #This is an instance method
    def take_book(self):
        print(f'{self.title} Book has been taken of the  shelf')
###########################
    #This is a class method 
    @classmethod
    def create(cls, title):
        pass

Using Class Methods and Attributes

Class attributes and methods are useful in certain situations. For instance, let's say we want to keep track of how many instances of the Book class have been created. We can add every book instance created to the all class attribute. Let's see how this will look in python.

class Book:
    #this a class attribute
    all = []
    def __init__(self, title):
        #these are the instance attribute
        self.id = None
        self.title = title
    #This is an instance method
    def take_book(self):
        print(f'{self.title} book has been taken of the  shelf')
    #This is a class method 
    @classmethod
    def create(cls, title):
      book = cls(title)
      book.id = len(cls.all)
      cls.all.append(book) 
      return book

Let's create a few Book instances and see how we use the class attributes and methods vs the instance attributes and methods.

Book.create("Remember me")
Book.create("The Fall")
Book.create("Parenting")
for book in Book.all:
    print('Book Name: ', book.title)

In the code above, we are creating a few books and then iterating through the all class attribute to print each book. A way you can tell a method is a class is when it is invoked on the class name and not the instance. Anytime you want to access a class attribute or method you use the class name, in this case you would use Book.create() and Book.all.

Using Instance Methods and Attributes

For instances of a class you call the methods and attributes on the instance of the class. Let's see how this looks in python.

remember_me = Book.create("Remember me")
remember_me.take_book()

Here we are creating a book and the create method will return an instance of that book and assign it to the remember_me variable. When we want to take the book we then invoke an instance method, take_book().

When to use Class Attributes and Methods

Class methods are useful in certain situation and play a vital role in Object Oriented Programming. You can use class attributes and methods when you don't need to depend on an instance of a class. It could make things a bit complex so using them sparingly would be ideal.

In conclusion, class methods and attributes are used when you want to call a class method without instantiating an instance of that class. Instance methods and attributes are used when you want to make something happen on an instance of a class. You can tell what is a class attribute or method and what is an instance attribute or method by looking at what is before the dot. If its the name of the class then it's a class attribute or method. If its the name of an instance then its an instance attribute or method.

0
Subscribe to my newsletter

Read articles from Ruth directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ruth
Ruth

I am a Full Stack Software Engineer with experience in leveraging a variety of technologies to find the easiest and most efficient and effective way to meet the needs of each application. My experience ranges from creating simple landing pages to developing complex interactive web applications. I believe my skills in communication, team work, and googling will contribute positively to your team.