lundi 20 juillet 2015

How to include macros in Python?

This is a similar question but my goal is not performance but readability.

Let's say I have different Behaviours, and they share a repeated function f1().

from abc import ABCMeta, abstractmethod

class Behavior:
    __metaclass__ = ABCMeta
    @abstractmethod 
    def run(self):
        pass

class Behavior1(Behavior):
    def __init__(self, data):
        self.data = data

    def run(self):
        def f1():
            print(self.data)

        f1()

class Behavior2(Behavior):
    def __init__(self, data):
        self.data = data

    def run(self):
        def f1():
            print(self.data)

        f1()

class Behavior3(Behavior):
    def __init__(self, data):
        self.data = data

    def run(self):
        def f1():
            print(self.data)

        f1()

I want f1() to have access to objects and data inside run() without passing them as arguments.

Is there any pythonic or OOP way of reusing f1() without passing arguments?

Aucun commentaire:

Enregistrer un commentaire