learn-python
60 строк · 2.6 Кб
1"""Class Definition Syntax.
2
3@see: https://docs.python.org/3/tutorial/classes.html#method-objects
4
5Classes can have two types of attribute references: data or methods. Class methods are called
6by [variable_name].[method_name]([parameters]) as opposed to class data which lacks the ().
7"""
8
9
10class MyCounter:11"""A simple example of the counter class"""12counter = 1013
14def get_counter(self):15"""Return the counter"""16return self.counter17
18def increment_counter(self):19"""Increment the counter"""20self.counter += 121return self.counter22
23
24def test_method_objects():25"""Method Objects."""26
27# The other kind of instance attribute reference is a method. A method is a function that28# “belongs to” an object. (In Python, the term method is not unique to class instances: other29# object types can have methods as well. For example, list objects have methods called append,30# insert, remove, sort, and so on. However, in the following discussion, we’ll use the term31# method exclusively to mean methods of class instance objects, unless explicitly stated32# otherwise.)33
34# But be aware that counter.get_counter() is not the same thing as MyCounter.get_counter() —35# it is a method object, not a function object.36
37# Usually, a method is called right after it is bound38counter = MyCounter()39assert counter.get_counter() == 1040
41# However, it is not necessary to call a method right away: counter.get_counter() is a method42# object, and can be stored away and called at a later time. For example:43get_counter = counter.get_counter44assert get_counter() == 1045
46# What exactly happens when a method is called? You may have noticed that counter.get_counter()47# was called without an argument above, even though the function definition for get_counter()48# specified an argument (self). What happened to the argument? Surely Python raises an49# exception when a function that requires an argument is called without any — even if the50# argument isn’t actually used…51
52# Actually, you may have guessed the answer: the special thing about methods is that the53# instance object is passed as the first argument of the function. In our example, the call54# counter.get_counter() is exactly equivalent to MyCounter.get_counter(counter). In general,55# calling a method with a list of n arguments is equivalent to calling the corresponding56# function with an argument list that is created by inserting the method’s instance object57# before the first argument.58
59assert counter.get_counter() == 1060assert MyCounter.get_counter(counter) == 1061