CodeGym /Courses /Python SELF EN /Creating Classes and Objects

Creating Classes and Objects

Python SELF EN
Level 15 , Lesson 3
Available

3.1 Creating a Class

Creating classes in Python is an essential part of object-oriented programming (OOP). Classes allow you to create new data types that can have their own attributes and methods. Let's cover the basic concepts and examples of creating classes in Python.

Basic Concepts

  • Class: A blueprint for creating objects. The class defines the attributes and methods that the objects of this class will have.
  • Object: An instance of a class. The object has all the attributes and methods defined in the class.
  • Attribute: A variable associated with a class or object.
  • Method: A function associated with a class or object.

Attributes are basically the internal variables of an object or class. Methods are the functions defined inside the class. These terms come from OOP and are used alongside functions and variables.

To declare (create) a new class, the keyword class is used. The general syntax looks like this:


class ClassName:
    variable1 = value1
    variableN = valueN
          
    def function1(self):
        function code
            
    def functionM(self):
        function code

In essence, you could say a class is a small program (variables + functions) placed in a separate named area — ClassName.

After you have created a class, you can create objects (instances) of this class. This code looks even simpler:


variableX = ClassName()

Important! Variable and method names in Python are generally written in lowercase. Class names are capitalized. Also, when writing class names, underscores are not used. If a class name needs to consist of multiple words, then each word is capitalized.

If you want to refer to a class/object variable, the code generally looks like this:


variableX.variable1 = 10
variableX.functionM()       

But there are some nuances to it, which we will talk about below…

3.2 Working with an Object

Both the class and an instance of the class (the class object) are objects, so both can have their own variables and methods.

There are two types of variables:

  • Class Attribute/Variable/Field (class property)
  • Object Attribute/Variable/Field (object property)

And three types of methods:

  • Class Method/Function (class method)
  • Instance Method/Function (instance method)
  • Static Method (static method)

Methods differ in how they are declared and how they are called.

Instance Methods

When declaring an instance method, you need to pass the first mandatory parameter — self. When you call the method, this parameter will receive a reference to the object (instance).


class MyClass:

    def instance_method(self):
        print(type(self))  # <class 'MyClass'>
                   

my_object = MyClass()
my_object.instance_method()
        

In the example above, when the function instance_method() began executing, the parameter self was passed a reference to the object my_object.

Class Methods

When declaring a class method, you also need to pass the first mandatory parameter — cls. When you call the method, this parameter receives a reference to the class (class object). Also, the class method should be marked with the decorator classmethod, as in the example below:


class MyClass:
    def instance_method(self):
        print(type(self))  # <class 'MyClass'>
        
    @classmethod
    def class_method(cls):
        print(type(cls))  # <class 'type'>
                   

my_object = MyClass()
my_object.instance_method()
MyClass.class_method()
        

In the example above, when the function class_method() began executing, the parameter cls was passed a reference to the class MyClass.

Static Method

When declaring a static method, you don't need to pass anything, but it also won't be able to access the internal data of the class. The method should be marked with the decorator staticmethod, as in the example below:


class MyClass:
    def instance_method(self):
        print(type(self))  # <class 'MyClass'>
        
    @classmethod
    def class_method(cls):
        print(type(cls))  # <class 'type'>
        
    @staticmethod
    def static_method():
        return "This method doesn't depend on the instance or class"
                   
my_object = MyClass()
my_object.instance_method()
MyClass.class_method()
MyClass.static_method() 
        

The static method is called very similarly to the class method, but neither object references nor class references are passed to it.

3.3 Class Variables

Class Variables

To declare a class variable (attribute), just declare it anywhere inside the class. Usually, this is done at the very beginning, before defining class methods. Example:


class MyClass:
    attribute = "I am a class attribute"
        
    @classmethod
    def class_method(cls):
        print(cls.attribute)  # I am a class attribute
                  
my_object = MyClass()
MyClass.class_method()

If you want to read or write a value to a class variable, then use the object cls.

In principle, you can also refer to a class variable through the class name:


class MyClass:
    attribute = "I am a class attribute"
        
    @classmethod
    def class_method(cls):
        print(MyClass.attribute)  # I am a class attribute
                  
my_object = MyClass()

print(MyClass.attribute)  # I am a class attribute

Instance/Object Variables

Instance variables (instance) are the fields of the self object. You simply work with them via self.name. The object self is passed to every instance method for this purpose.

Example:


class MyClass:
    attribute = "I am a class attribute"
        
    def set_name(self, name):
        self.name = name
        
    def print_name(self):
        print(self.name)    
                 
my_object = MyClass()
my_object.set_name("Object field named name") 
my_object.print_name()  # "Object field named name"
        

Every time you call an instance method, the first parameter (self) is passed a reference to the object on which you call the method. Different instance methods can access common data by using the self object.

2
Task
Python SELF EN, level 15, lesson 3
Locked
Creating objects.
Creating objects.
2
Task
Python SELF EN, level 15, lesson 3
Locked
Create classes.
Create classes.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION