Is there any Python equivalent to partial classes?

前端 未结 9 1605
無奈伤痛
無奈伤痛 2020-11-27 15:31

Using \"new\" style classes (I\'m in python 3.2) is there a way to split a class over multiple files? I\'ve got a large class (which really should be a single class from an

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-27 16:22

    I've previously toyed around with something similar. My usecase was a class hierarchy of nodes in an abstract syntax tree, and then I wanted to put all e.g. prettyprinting functions in a separate prettyprint.py file but still have them as methods in the classes.

    One thing I tried was to use a decorator that puts the decorated function as an attribute on a specified class. In my case this would mean that prettyprint.py contains lots of def prettyprint(self) all decorated with different @inclass(...)

    A problem with this is that one must make sure that the sub files are always imported, and that they depend on the main class, which makes for a circular dependency, which may be messy.

    def inclass(kls):
        """
        Decorator that adds the decorated function
        as a method in specified class
        """
        def _(func):
            setattr(kls,func.__name__, func)
            return func
        return _
    
    ## exampe usage
    class C:
        def __init__(self, d):
            self.d = d
    
    # this would be in a separate file.
    @inclass(C)
    def meth(self, a):
        """Some method"""
        print "attribute: %s - argument: %s" % (self.d, a)
    
    i = C(10)
    print i.meth.__doc__
    i.meth(20)
    

提交回复
热议问题