Classes, Methods, and Polymorphism in Python

I created a prototype module to create complex timer schedules in python. Class prototypes emulate Timer objects, each with its own waiting time, repeat the objects that group Timer and other Repeat objects, and the Schedule class, only to contain entire constructions or instances of Timers and Repeat. The design can be complex as needed and must be flexible.

Each of these three classes has a method .run()that allows you to go through the entire schedule. Regardless of the class, the method .run()starts a timer, a repeated group for a certain number of iterations, or a schedule.

Is this polymorphism-oriented approach sound or dumb? What are other suitable approaches that I should consider in order to create such a universal utility that makes it easy to combine all the building blocks as difficult as possible?

Thank!

Here is the module code:

#####################
## Importing modules

from time import time, sleep


#####################
## Class definitions

class Timer:
    """
    Timer object with duration.

    """
    def __init__(self, duration):
        self.duration = duration
    def run(self):
        print "Waiting for %i seconds" % self.duration
        wait(self.duration)
        chime()

class Repeat:
    """
    Repeat grouped objects for a certain number of repetitions.

    """
    def __init__(self, objects=[], rep=1):
        self.rep = rep
        self.objects = objects
    def run(self):
        print "Repeating group for %i times" % self.rep
        for i in xrange(self.rep):
            for group in self.objects:
                group.run()

class Schedule:
    """
    Groups of timers and repetitions. Maybe redundant with class Repeat.

    """
    def __init__(self, schedule=[]):
        self.schedule = schedule
    def run(self):
        for group in self.schedule:
            group.run()

########################
## Function definitions

def wait(duration):
    """
    Wait a certain number of seconds.

    """
    time_end = time() + float(duration) #uncoment for minutes# * 60
    time_diff = time_end - time()
    while time_diff > 0:
        sleep(1)
        time_diff = time_end - time()

def chime():
    print "Ding!"
+3
source share
3 answers

This is called duck typing and is used in Python all the time.

+3
source

The duck seal approach is perfect. If you want to check whether this class should work in your structure, you can use Abstract base classes (Python 2.6 is required), PEP 3119:

[...] , . , : " ?", "list", " getitem". , , , . [...] PEP , , ABC. ABC - Python, , . isinstance(), ABC , .

ABC isinstance issubclass , :

from abc import ABCMeta, abstractmethod

class Runnable(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def run(self):
        raise NotImplementedError

 class Schedule(Runnable):
     ...

, ( , ) runnables, isinstance issubclass :

  >>> issubclass(SomeOtherClass, Runnable)
  False
  >>> Runnable.register(SomeOtherClass)
  >>> issubclass(SomeOtherClass, Runnable)
  True
+5

It is really used all the time and is excellent. If you want to be very careful, you can use hasattrto make sure that the object you expect to have a method runactually has one pretty early period. This helps ensure that exceptions are thrown as close as possible to the point of error.

But otherwise it’s normal and often done.

+2
source

Source: https://habr.com/ru/post/1729843/


All Articles