我使用拷贝构造函数寻找一种方法来初始化派生类和()运算符类似于C++的Python:多重继承,拷贝构造函数,类的初始化和()超载
class Rectangle {
int width, height;
public:
Rectangle (int,int);
int area() {return (width*height);}
};
Rectangle::Rectangle (int a, int b) {
width = a;
height = b;
}
r = Rectangle(2,3)
s = Rectangle(r) /* <--using copy constructor to initialize*/
,然后我就在想我将如何实现intitialisation的情况下,这种方式我已经从自己的另外两个多名会员和派生类想出了如下:
class MyBase1(object):
def __init__(self, *args, **kwargs):
self.x = kwargs.get('x')
self.y = kwargs.get('y')
print("mybase1 {}".format(kwargs))
def print_base1(self):
pass
class MyBase2(object):
def __init__(self, *args, **kwargs):
self.s = kwargs.get('s')
self.p = kwargs.get('p')
print("mybase2 {}".format(kwargs))
def print_base2(self):
pass
class MyChild(MyBase1, MyBase2):
def __init__(self, **kwargs):
MyBase1.__init__(self, **kwargs)
MyBase2.__init__(self, **kwargs)
self.function_name = kwargs.get('function')
def __call__(self, my_base1, my_base2, **kwargs):
initialization_dictionary = dict(vars(my_base1), **vars(my_base2))
initialization_dictionary = dict(initialization_dictionary, **kwargs)
newInstance = MyChild(**initialization_dictionary)
return newInstance
调用,则:
base1 = MyBase1(x=1, y=2)
base2 = MyBase2(s=3, p=4)
child = MyChild()(base1, base2, function='arcsine') #<--initialising
[stm for stm in dir(child) if not stm.startswith('__')]
# gives:['function_name', 'p', 'print_base1', 'print_base2', 's', 'x', 'y']
vars(child)
# gives:{'function_name': 'arcsine', 'p': 4, 's': 3, 'x': 1, 'y': 2}
所以我想知道这是多么非pythonic的方式?如果有更好的方法(或者无法做到这一点)?
在Python中,您将定义一个'__copy__'和'__deepcopy__'特殊方法,用于'copy.copy'和'copy.deepcopy'函数。 –
例如,请参见[此问题](http://stackoverflow.com/questions/15684881/python-implementation-of-shallow-and-deep-copy-constructors) –