Methods in Python
Introduction
This is a continuation of the article
«Classes»
from the section
«OOP in Python»
.
Here you can read about ordinary methods. Such methods are also called instance methods.
classmethods
can be studied
here
Methods are functions inside classes. The arguments that a method accepts are the class object and some other arguments needed
for this method.
In simple terms, a method cannot be called "from the street"; first you need to say at least which class you need
to work with.
In the case of ordinary methods, you also need to pass the class object.
Difference between a method and a function
A method here means an ordinary method, not a static method and not a classmethod
A method is a function within some class.
A method expects to be applied to an object of its class
By default, a method must be passed an object of its class.
A function expects certain arguments to be passed to it, or works with no arguments at all
The arguments can be both standard objects and objects
of a user-defined class.
This is determined when the function is declared
You can pass nothing at all to a function that has no parameters, and it will still work.
Example
Let us write a method for the Site class that will simply print information about the object to the screen.
class Site(): def describe(self): print(f"Website {self.name} is available at {self.url} and was created in {self.established}") pass hh = Site() hh.url = "https://www.heihei.ru" hh.name = "HeiHei.ru" hh.established = 2018 hh.describe()
python method_example.py
Website HeiHei.ru is available at https://www.heihei.ru and was created in 2018
The method works, but if, for example, you forget to set one of the attributes, the object is still created, but the method no longer works
# hh.established = 2018
python method_example.py
Traceback (most recent call last): File "/home/andrei/python/method_example.py", line 12, in <module> hh.describe() File "/home/andrei/python/method_example.py", line 3, in describe print(f"Website {self.name} is available at {self.url} and was created in {self.established}") AttributeError: 'Site' object has no attribute 'established'
To make objects created immediately with all the necessary attributes, and also to reduce the amount of code and to be able to combine different attributes right away, the method is used __init__()
__init__()
The method __init__() allows you to create objects of this class faster.
Compare the two classes Site without __init__() and WebSite with __init__()
class Site(): pass hh = Site() hh.url = "https://www.heihei.ru" hh.name = "HeiHei.ru" hh.description = "Holiday site" hh.established = 2018 tb = Site() tb.url = "https://www.topbicycle.ru" tb.name = "TobBicycle" tb.description = "Bicycle reviews" tb.established = 2018 print(hh.url, hh.name, hh.description, hh.established) print(tb.url, tb.name, tb.description, tb.description) class WebSite(): def __init__(self, url, name, description, established): self.url = url self.name = name self.description = description self.established = established hh = WebSite("https://www.heihei.ru", "HeiHei.ru", "Holiday site", 2018) tb = WebSite("https://www.topbicycle.ru", "TobBicycle.ru", "Bicycle reviews", 2018) print(hh.url, hh.name, hh.description, hh.established) print(tb.url, tb.name, tb.description, tb.description)
python init_example.py
https://www.heihei.ru HeiHei.ru Holiday site 2018 https://www.topbicycle.ru TobBicycle.ru Bicycle reviews Bicycle reviews https://www.heihei.ru HeiHei.ru Holiday site 2018 https://www.topbicycle.ru TobBicycle.ru Bicycle reviews Bicycle reviews
The method __init__() also allows creating additional attributes from those already set
Let us look at the class Employee, and the method __init__() which will take just two arguments, first name (first) and last name (last)
class Employee: def __init__(self, first, last): self.first = first self.last = last self.fullname = first + ' ' + last self.email = first + '.' + last + '@vostok.su' emp_1 = Employee('Yuri', 'Gagarin') emp_2 = Employee('Test', 'User') print(f"{emp_1.fullname} email is {emp_1.email}") print(f"{emp_2.fullname} email is {emp_2.email}")
python init_example.py
Yuri Gagarin email is Yuri.Gagarin@vostok.su Test User email is Test.User@vostok.su
With the method __init__() we effortlessly created the attributes full name (fullname) and email (email)
Default values
With __init__() you can specify the values that the attributes will receive if they are not set
when the object is created.
In the following example, you can create objects of the Cosmonaut class both with and without specifying the cosmonaut's first name. A last name alone
is enough.
class Cosmonaut: def __init__(self, last, first = "Cosmonaut"): self.last = last self.first = first self.fullname = first + ' ' + last self.email = first + '.' + last + '@vostok.su' cosm_1 = Cosmonaut('Gagarin') cosm_2 = Cosmonaut('Alexei', 'Leonov') print(f"{cosm_1.fullname} email is {cosm_1.email}") print(f"{cosm_2.fullname} email is {cosm_2.email}")
python init_example.py
Cosmonaut Gagarin email is Cosmonaut.Gagarin@vostok.su Leonov Alexei email is Leonov.Alexei@vostok.su
Let us summarize the advantages of __init__()
- Less code
- You can set default values → all required attributes will be in place
- The ability to combine attributes into new ones right while the object is being created
self
A few more words about self
Consider the script
method_example.py
class Dog(): bioclass = "mammal" def __init__(self, breed, name, spots): self.breed = breed self.name = name self.spots = spots def bark(self): print("WOOF!") my_dog = Dog("husky", "Barbos", True) my_dog.bark()
python method_example.py
WOOF!
What happens if you remove from
def bark(self):
self, leaving
def bark():
python method_example.py
Traceback (most recent call last): File "/home/andrei/python/method_example.py", line 14, in <module> my_dog.bark() TypeError: bark() takes 0 positional arguments but 1 was given
It would seem that we did not pass any arguments to bark() at all. Nevertheless, one was passed automatically. And that is because the expression
my_dog.bark()
This is the short form
Dog.bark(my_dog)
That is, an object of this class is expected to be passed to the method. That is why you need to specify
def bark(self):
And not
def bark():
Example of using the methods of the list class
Let us look at a list in interactive mode
python
>>> mylist = [1,2,3] >>> mylist.append(4) >>> mylist [1, 2, 3, 4] >>> mylist.pop() 4 >>> mylist [1, 2, 3] >>> help(mylist.insert) Help on built-in function insert: insert(index, object, /) method of builtins.list instance Insert object before index.
Article author: Andrei Olegovich