Python: multiple inheritance and __add __ () in a base class

I have a base class where I want to process __add__()and want to support when __add__with two instances of a subclass that have methods of both subclasses in the resulting instance.

import copy

class Base(dict):
    def __init__(self, **data):
        self.update(data)

    def __add__(self, other):
        result = copy.deepcopy(self)
        result.update(other)
        # how do I now join the methods?
        return result

class A(Base):
    def a(self):
        print "test a"

class B(Base):
    def b(self):
        print "test b"


if __name__ == '__main__':
    a = A(a=1, b=2)
    b = B(c=1)
    c = a + b
    c.b() # should work
    c.a() # should work

Change . To be more specific: I have a class Hoststhat contains dict(host01=.., host02=..)(hence a subclassification dict) - this offers some basic methods, such asrun_ssh_commmand_on_all_hosts()

Now I have a subclass HostsLoadbalancerthat contains some special methods, such as drain(), and I have a class HostsNagiosthat contains some nagios-specific methods.

What I do then is something like:

nagios_hosts = nagios.gethosts()
lb_hosts = loadbalancer.gethosts()
hosts = nagios_hosts + lb_hosts
hosts.run_ssh_command_on_all_hosts('uname')
hosts.drain() # method of HostsLoadbalancer - drains just the loadbalancer-hosts
hosts.acknoledge_downtime() # method of NagiosHosts - does this just for the nagios hosts, is overlapping

What is the best solution for this problem?

, - " " - :    x in dir ():       setattr (self, x, getattr (other, x))

? ?

+3
2

, . . python, , , , . :

import copy

class Base(dict):
    global_class_cache = {}

    def __init__(self, **data):
        self.local_data = data

    def __add__(self, other):
        new_instance = self._new_type((type(self), type(other)))()
        new_instance.update(copy.deepcopy(self).__dict__)
        new_instance.update(copy.deepcopy(other).__dict__)
        return new_instance

    def _new_type(self, parents):
        parents = tuple(parents)
        if parents not in Base.global_class_cache:
            name = '_'.join(cls.__name__ for cls in parents)
            Base.global_class_cache[parents] = type(name, parents, {})
        return Base.global_class_cache[parents]

class A(Base):
    def a(self):
        print "test a"

class B(Base):
    def b(self):
        print "test b"


if __name__ == '__main__':
    a = A(a=1, b=2)
    b = B(c=1)
    c = a + b
    c.b() # should work
    c.a() # should work
    print c.__class__.__name__

UPDATE , - mixins.

+1

. Base , . , , , say_hola(), say_hola():

class Base(object):
   def say_hola(self):
     print "hola"

class C1(Base):
   def add(self, a, b):
      return a+b

class C2(Base):
   def say_bonjour(self):
      return 'bon jour'

, C1 C2 say_hola() .

- Mixin. :

- , mixin - , , ). mixin , . .

0

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


All Articles