learn-python

Форк
0
/
test_method_objects.py 
60 строк · 2.6 Кб
1
"""Class Definition Syntax.
2

3
@see: https://docs.python.org/3/tutorial/classes.html#method-objects
4

5
Classes can have two types of attribute references: data or methods. Class methods are called
6
by [variable_name].[method_name]([parameters]) as opposed to class data which lacks the ().
7
"""
8

9

10
class MyCounter:
11
    """A simple example of the counter class"""
12
    counter = 10
13

14
    def get_counter(self):
15
        """Return the counter"""
16
        return self.counter
17

18
    def increment_counter(self):
19
        """Increment the counter"""
20
        self.counter += 1
21
        return self.counter
22

23

24
def test_method_objects():
25
    """Method Objects."""
26

27
    # The other kind of instance attribute reference is a method. A method is a function that
28
    # “belongs to” an object. (In Python, the term method is not unique to class instances: other
29
    # 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 term
31
    # method exclusively to mean methods of class instance objects, unless explicitly stated
32
    # 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 bound
38
    counter = MyCounter()
39
    assert counter.get_counter() == 10
40

41
    # However, it is not necessary to call a method right away: counter.get_counter() is a method
42
    # object, and can be stored away and called at a later time. For example:
43
    get_counter = counter.get_counter
44
    assert get_counter() == 10
45

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 an
49
    # exception when a function that requires an argument is called without any — even if the
50
    # argument isn’t actually used…
51

52
    # Actually, you may have guessed the answer: the special thing about methods is that the
53
    # instance object is passed as the first argument of the function. In our example, the call
54
    # 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 corresponding
56
    # function with an argument list that is created by inserting the method’s instance object
57
    # before the first argument.
58

59
    assert counter.get_counter() == 10
60
    assert MyCounter.get_counter(counter) == 10
61

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.