The book "How is Python. Guide for developers, programmers and interested »

    imageHi Habrozhiteli! We recently released a new book about Python. We offer immediately read the introductory material.

    Excerpt 7.4. Using IDLE


    Since IDLE includes REPL, you can enter the code below and analyze it directly into the REPL. However, you can also write code, run it, and analyze from the REPL. To try out this feature, open a new file and include the following code:

    name = "Matt"
    first = name
    age = 1000
    print(id(age))
    age = age + 1
    print(id(age))
    names = []
    print(id(names))
    names.append("Fred")
    print(id(names))

    Save the code in a file with the name iden.py. Run the file. In IDLE, to do this, press the F5 key. Four numbers will be displayed in the REPL. The first two will be different; this means that the integer is immutable. The last two numbers are the same. This is explained by the fact that despite the change in the names list, the identifier remains the same. In general, this fact is nothing fundamentally new.

    Now the most interesting thing: if you enter the dir () command in the REPL, it will output a list of variables. You will see that global variables from iden.py are now available.

    REPL in IDLE allows access to all global variables. You can view name and names, and even call functions or methods — for example, names.append ("George").

    Having the opportunity to study the results of the just executed code, you can quickly analyze the code and experiment with it. Experienced Python developers often write code to the REPL, insert it into the file, run the file again, write new code to the REPL, and continue to write code in this way.

    image

    image

    image

    Excerpt 22. Subclassing


    In addition to grouping state and operations, classes also provide code reuse. If you already have a class, and you need another class that is slightly different in its behavior, one of the ways to reuse it is to subclass. The class from which subclassing is performed is called the superclass (another common name for the superclass is the parent class).

    Suppose you want to create a chair that can seat six skiers. To create the class Chair6, a modeling chair for six people, a more specialized version of the Chair, you can use subclassing. Subclasses allow the programmer to inherit the methods of the parent classes and override the methods that need to be changed.

    Below is the class Chair6, which is a subclass of CorrectChair:

    >>> class Chair6(CorrectChair):
    ... max_occupants = 6

    Note that the parent class CorrectChair is enclosed in parentheses after the class name. Note that Chair6 does not define a constructor in its body, however you can create instances of the class:

    >>> sixer = Chair6(76)

    How does Python create an object if a constructor is not defined in the class? Here's what happens: when Python searches for the .__ init__ method, the search begins with Chair6. Since the Chair6 class contains only the max_occupants attribute, Python will not find the .__ init__ method here. But since Chair6 is a subclass of CorrectChair, it has an __bases__ attribute with a list of base classes that are concatenated into a tuple:

    image

    image

    >>> Chair6.__bases__
    (__main__.CorrectChair,)

    Python then looks for a constructor in the base classes. He finds a constructor in CorrectChair and uses it to create a new class.

    The same search happens when you call .load for an instance. An instance does not have an attribute corresponding to the method name, so Python checks the instance class. In Chair6, there is also no .load method, so Python is looking for an attribute in the base class CorrectChair. Here, the .load method is called with too large a value, which results in a ValueError error:

    >>> sixer.load(7)
    Traceback (most recent call last):
       File "/tmp/chair.py", line 30, in <module>
         sixer.load(7)
       File "/tmp/chair.py", line 13, in load
         new_val = self._check(self.count + number)
       File "/tmp/chair.py", line 23, in _check
         number))
    ValueError: Invalid count:7

    Python finds a method in the base class, but calling the ._check method results in a ValueError error.

    22.1. Stop counting


    Sometimes the skier fails to get on the lift normally. In such cases, the operator slows down or stops the lift to help the skier. We can use Python to create a new class that will count the number of such stops.

    Suppose each time a .load is called, a function must be called that returns a logical indication that a stop has occurred or not. In the parameters of the function, the number of skiers and the object of the chair are transmitted.

    Below is the class that gets the is_stalled function in the constructor. This function will be called each time .load calls:

    >>> class StallChair(CorrectChair):
    ...          def __init__(self, id, is_stalled):
    ...               super().__init__(id)
    ...               self.is_stalled = is_stalled
    ...               self.stalls = 0
    ...
    ...          def load(self, number):
    ...                if self.is_stalled(number, self):
    ...                    self.stalls += 1
    ...                super().load(number)

    To create an instance of this class, you must provide the is_stalled function. The following simple function generates stops in 10% of cases:

    >>> import random
    >>> def ten_percent(number, chair):
    ...           """Return True 10% of time"""
    ...           return random.random() < .1

    Now you can create an instance by specifying the ten_percent function as the is_stalled parameter:

    >>> stall42 = StallChair(42, ten_percent)

    22.2. super


    Recall that StallChair defines its own method .__ init__, which is called when an instance is created. Note: the first line of the constructor looks like this:

    super().__init__(id)

    When you call super inside a method, you get access to the correct parent class.

    A string in the constructor allows you to call the constructor CorrectChair. Instead of repeating the logic of assigning the id and count attributes, you can use logic from the parent class. Since StallChair has additional attributes that need to be set for an instance, this can be done after calling the parent constructor.

    image

    The .load method also contains a super call:

    def load(self, number):
          if self.is_stalled(number, self):
              self.stalls += 1
          super().load(number)

    In the .load method, you call the is_stalled function to determine if the elevator has stopped, then transfer control of the original .load functionality from CorrectChair using super.

    Placing the common code in one place (in the base class) reduces the number of errors and code duplications.

    about the author


    Matt Harrison has been using Python since 2000. He leads MetaSnake, a consultancy and corporate training in Python and data analysis theory. In the past, he worked in the areas of research, assembly management and testing, business intelligence and data storage.

    He gave presentations and training lectures at conferences such as Strata, SciPy, SCALE, PyCON and OSCON, as well as at local user conferences. The structure and material of this book is based on his practical experience in teaching Python. Matt periodically publishes useful information related to Python (@__mharrison__) on Twitter.

    Scientific editors


    Roger E. Davidson (Roger A. Davidson) is currently the Dean of the Faculty of Mathematics at American River College (Sacramento, California). His doctoral thesis was written on the subject of aerospace engineering, but he also holds computer science, electrical engineering and systems engineering diplomas, and also recently received a certificate in data science (which is where his Python passion began). Throughout his career, Roger worked at NASA, in Fortune 50 companies, in start-ups and community colleges. He is enthusiastic about education, science (not just data processing), blackberry pies and leadership of heterogeneous teams in solving large problems.

    Andrew McLaughlin (AndrewMcLaughlin)- programmer and designer, system administrator in the first half of the day and family man in the second. Because of her attention to detail, she has been involved in web programming since 1998. A graduate with honors from George Fox University, Andrew received a degree in management and information systems. In his spare time, he goes on camping trips with his wife and two children, and also sometimes works in a carpentry workshop (all fingers are still in place). Read his Twitter posts: @amclaughlin.

    »For more information on the book, please visit the publisher's website.
    " Table of Contents
    " Excerpt

    For Habrozhiteley 20% discount on the coupon - Python .

    Also popular now: