Classes in Python

Introduction

Classes should be named with a capital letter and use CamelCase.

A new class is created with class

An object of this class is created using =

object = ClassName()

The simplest example of usage

class Sample(): pass my_sample = Sample() print(type(my_sample))

<class '__main__.Sample'>

Classes without attributes and methods are practically useless.

Attributes

Attributes are properties of an object. An everyday example: a bicycle has country of manufacture , mass, color, number of speeds, price and so on.

A website on the internet has a url, the year the domain was delegated, an author, a main topic.

To create attributes it is enough to declare a class and create an object.

The syntax for creation and for access is as follows

object.attribute_name

Let's create a class Site and an object hh with the site address.

class Site(): pass hh = Site() hh.url = "https://www.heihei.ru"

class Employee: pass emp_1 = Employee() emp_2 = Employee() print(emp_1) print(emp_2) emp_1.first = 'Yuri' emp_1.last = 'Gagarin' emp_1.email = 'Yuri.Gagarin@vostok.su' emp_1.pay = 1000 emp_2.first = 'Test' emp_2.last = 'User' emp_2.email = 'Test.User@vostok.su' emp_2.pay = 1234 print(emp_1.email) print(emp_2.email)

python emp_ex.py

<__main__.Employee object at 0x7fca67c26fd0> <__main__.Employee object at 0x7fca67c26fa0> Yuri.Gagarin@vostok.su Test.User@vostok.su

Also, to create attributes you need to use the method __init__() in this case, every time a new object of this class is created, the __init__() method is called first

Let's create a class Dog that will have one attribute - breed.

When a class is created it can have any name, but inside the class, to set the value of an attribute the keyword is used self

self.attribute = value

Thus, if you change the name of the class, nothing inside needs to be renamed.

class Cat(): def __init__(self, breed): self.breed = breed

Renaming Cat to Dog

class Dog(): def __init__(self, breed): self.breed = breed

If a class has an attribute, you need to be more careful when creating an object

my_dog = Dog()

This will no longer work

Traceback (most recent call last): File "/home/andrei/python/sample.py", line 6, in <module> my_dog = Dog() TypeError: __init__() missing 1 required positional argument: 'breed'

Now when creating an object you need to specify the desired value of the attribute

my_dog = Dog("husky")

Or in the __init__() method you need to specify a default value

class Dog(): def __init__(self, breed="aidi"): self.breed = breed

The following line may seem strange to beginners

self.breed = breed

The main thing to grasp here is the following:

It is self.breed - that sets the name of the attribute that the object of this class will have.

In this case the attribute will be called breed

breed - this is the name of the parameter of the __init__() method.

In this case - the first argument passed by you to the __init__() method is called breed

You can also name it differently, for example arg1, the essence will not change from this, but if there are many of them - it will become harder to remember which attribute corresponds to, say, arg99.

class Dog(): def __init__(self, agr1): self.breed = arg1

Now I will try to explain the same thing, but a little differently and with two attributes

class Dog: def __init__(self, name, age): self.name = name self.age = age

What comes after the dot is the name of the attribute. It is needed in order to access this attribute later.

I have highlighted the names of the parameters in green. Often in examples the attribute and the parameter have the same names. This is not a mandatory condition, which can hinder understanding of the essence.

Compare the following class declarations.

Only formal names from which nothing is clear

class Dog: def __init__(self, arg1, arg2): self.attr1 = arg1 self.attr2 = arg2 pet = Dog("Tuzik", 2) print(pet.attr1) print(pet.attr2)

Clear names, but they are different for the attributes and for the __init__() parameters

class Dog: def __init__(self, name, age): self.nick = name self.years = age pet = Dog("Tuzik", 2) print(pet.nick) print(pet.year)

Clear and identical names

class Dog: def __init__(self, name, age): self.name = name self.age = age pet = Dog("Tuzik", 2) print(pet.name) print(pet.age)

The result of the call is the same for all three variants

Tuzik
2

An example with three attributes

class Dog(): def __init__(self, breed, name, spots): self.breed = breed self.name = name self.spots = spots # my_dog = Dog() my_dog = Dog("husky", "Barbos", True) print(my_dog.breed, my_dog.name, my_dog.spots)

Static attributes

You can set attributes for all elements of a class at once. They are called static (static attributes, class object attributes)

class Dog(): # CLASS OBJECT ATTRIBUTE # SAME FOR ANY INSTANCE OF A CLASS bioclass = "mammal" def __init__(self, breed, name, spots): self.breed = breed self.name = name self.spots = spots # When creating an object, the static attribute need not be specified explicitly my_dog = Dog("husky", "Barbos", True) # Check the default value of bioclass print(Dog.bioclass, my_dog.bioclass) # Override the value of bioclass for my_dog my_dog.bioclass = "super mammal" print(Dog.bioclass, my_dog.bioclass)

mammal mammal
mammal super mammal

Objects

All classes in Python except Exception inherit from object

>>> o = object()
>>> dir(o)

['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Article author: Andrei Olegovich