开发者

How do I implement 'Parameter Object' refactor in Python?

Right now I use the parameter object's class to be inherited like so

class A():
    def __init__(self,p1,p2):
        self.p1, self.p2 = p1, p2

class B(A):
    def __init__(self,开发者_运维知识库b):
        self.p1, self.p2 = b.p1, b.p2

This trims up the absurdity of using the code but not the class code itself. So, I'd like to do the C++ thing and pass the parameter object to the initialization list like so

class A { 
    int p1,p2; 
}
class B : public A { 
    B(const A& a) : A(a) {} 
}

Can I do this in Python? Specifically, can I set the attributes of a parent class by somehow calling it's __init__ within the child's? - from reading "Dive into Python" I'd guess I can do this since the object is already constructed by the time __init__ is called.

Or, perhaps is there some different method of implementing the parameter object refactor in Python (and I'm just trying to force a C++ technique)?


Generally speaking, you likely don't need the parameter object refactor technique. Python has several collections in the standard library that already have the core benefits that a parameter object refactor would provide.

Additionally, the cost/benefit analysis for a refactor like the parameter object design pattern is notably different than C++. For instance, without static compilation, object creation and member lookups are much more expensive. The base case of the parameter object pattern is to provide a namespace for related fields, something that can be accomplished simply enough in Python with a dictionary.

The pattern has more value in Python if you need some kind of model manipulation in the form of methods that are related to the grouped data, but even then mechanisms as simple and inexpensive as "properties" can solve manipulation needs on member attributes.

With a slightly more detailed description of the problem space, we can probably help evaluate whether this sort of refactor is a benefit, but most likely you'd be better not using that design pattern when working in Python.


The translation of the C++ code into python would be something like:

class A():
    def __init__(self,p1,p2):
        self.p1, self.p2 = p1, p2

class B(A):
    def __init__(self,b):
        A.__init__(self, b.p1, b.p2)


class B(A):
    def __init__(self, *args, **kwargs):
        super(B, self).__init__(*args, **kwargs)

Read more about super() for details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜