Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中初始化对象的子对象_Python_Python 3.x_Python 2.7 - Fatal编程技术网

在Python中初始化对象的子对象

在Python中初始化对象的子对象,python,python-3.x,python-2.7,Python,Python 3.x,Python 2.7,让我们有一个类A的对象x(可能有“私有”字段,我不知道),我正在创建一个类B: class B(A): # ... class A(): def __init__(self, variable): self.variable = variable class B(A): def __init__(self, *args, **kwargs): super(self.__class__, self).__init__(*args, **k

让我们有一个类
A
的对象
x
(可能有“私有”字段,我不知道),我正在创建一个类
B

class B(A):
    # ...
class A():
    def __init__(self, variable):
        self.variable = variable

class B(A):
    def __init__(self, *args, **kwargs):
        super(self.__class__, self).__init__(*args, **kwargs)
现在我想创建一个类
B
的对象
y
,其
A
部分等于
x


如何在Python(2.x和3.x)中实现这一点?

我不知道自己是否理解得很好,但我认为在
类B中需要这个:

class A():
    def __init__(self, variable):
        self.variable = variable

class B(A):
    def __init__(self, *args, **kwargs):
        super(self.__class__, self).__init__(*args, **kwargs)
每次您从B实例化一个新对象时,它都会初始化
a中的所有属性。如果需要属性列表:

y = B(variable="123...")
attrs = y.__dict__.keys()

您是否知道要复制到
y
x
部分的属性?@stephernauch问题是我不知道这些属性,或者更糟糕的是,这些属性可能会在
a
的未来版本中发生更改。我知道,使用Python无法直接做到这一点。有多种方法可以做到这一点,但这在很大程度上取决于
A
B
的实现方式。如果您希望
B
对象具有
A
对象的所有私有字段值,您可以执行:
B.\u dict\uuuuu.update(A.\uu dict\uuuu)
。对象
a
本身不能被
b
x
神奇地“包装”对象已经存在。我不能像你建议的那样创造它