Defining a class in Python

When first learning python you will most likely use its imperative programming features since this makes it easy to get started. However, Python also supports object-oriented programming in the form of classes, objects, inheritance, etc.

This short article will show you how to define a class in Python. Start by defining the class header which comprises the name of the class followed by a colon:

class Animal:
     

It's conventional to name classes beginning with an uppercase character, and if compound words are needed then to use camel-case (e.g., FarmAnimal).

In order to create an object of any class we need a constructor, which can optionally accept one or more parameters. Even if the constructor doesn't need any parameters you still need to define a reference to the current object, which is conventionally called self:

class Animal:

    def __init__(self): 

Note that there are two underscore characters either side of the init.

Inside the constructor we can assign values to any attributes of the class, such as the name of animal: 

class Animal:

    def __init__(self):
        self._name = 'Fido' 

Note the variable name is prefixed with an underscore. This is optional, but is conventionally used to signify that the variable is intended to be private to the class.

Note also that the variable name _name is qualified by prefixing it with self. which is needed to ensure the value ('Dog' in this case) is assigned to the attribute of this class.

We can now write a method to access the variable we defined. A method operates similar to a function in that it is defined using def, but it also requires the self parameter and only exists within the context of the class.

Let's write a simple method that just prints the name of the animal:

class Animal:

    def __init__(self):
        self._name = 'Fido'
        
    def print_name(self):
        print(self._name) 

We can now, outside of the class, create an object of type Animal and invoke its print_name() method to see the results:

pet = Animal()
pet.print_name() 

Note that we did not need to pass any parameter values to either the constructor or the method. This is because the declaration of self is only needed within the class definition, not when being called.

Rather than always creating animals called Fido, we can enhance the constructor to require the caller to specify its name. Change the constructor code as follows:

def __init__(self, name):
    self._name = name 

We now need to provide the name of the animal when instantiating objects of type Animal:

pet = Animal('Fido')
pet.print_name()

another_pet = Animal('Tiddles')
another_pet.print_name() 

 If we want 'Fido' to be the default name then we can specify this as part of the constructor definition:

def __init__(self, name = 'Fido'):
    self._name = name 

Now, if we want the animal to be called Fido we don't need to pass a value when instantiating the object, but otherwise we just say what the name should be:

pet = Animal() # name defaults to 'Fido'
pet.print_name()

another_pet = Animal('Tiddles')
another_pet.print_name() 

If you are familiar with other object-oriented languages then you will know the concept of getter and setter methods. This provides a means to both return the value of a property and change its value, respectively.

Returning a property value means the client can do what they want with the value, so it is more flexible than providing the print_name() method above. Allowing the value to be changed is also often useful.

A property (sometimes referred to an an attribute) is a data type that the class is comprised of.

Let's firstly look at how we can make the _name variable a property and provide its getter method: 

@property
def name(self):
    return self._name 

The @property annotation decorator marks the method name as representing a property (i.e., attribute) of the Animal class. All we need to so is return its current value.

Client programs can obtain the value as follows:

another_pet = Animal('Tiddles')
print(another_pet.name)
 
If you wish, you could remove the print_name() method that was defined earlier, as our above getter method provides the more flexible alternative.

To define a setter method for the name property, you can use the following code where the method is decorated with @name.setter which tells Python that this is the corresponding setter method for the name property:

@name.setter
def name(self, value):
    self._name = value 

In client programs you can now change the name as follows:

another_pet.name = 'Bonzo' 

Depending on the nature of the property it might not be sensible to allow its value to change after construction, so always weigh up whether a setter method is needed.

The complete code for the Animal class follows:

class Animal:
    
    def __init__(self, name = 'Fido'):
        self._name = name

    @property
    def name(self):
        return self._name
    
    @name.setter
    def name(self, value):
        self._name = name 

Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

 

Comments

No comments made yet. Be the first to submit a comment
Monday, 27 October 2025

Captcha Image