Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.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 - Fatal编程技术网

Python 如何将扩展父类的属性获取到其嵌套子类?

Python 如何将扩展父类的属性获取到其嵌套子类?,python,python-3.x,Python,Python 3.x,我需要从Class A继承属性self.driver,实例从Class C扩展到Class B 我尝试的是: class A(C): def __init__(self, driver): super().__init__(driver) class B: def __init__(self, *args, n=3): self.somethingA = args[0] self.something

我需要从
Class A
继承属性
self.driver
,实例从
Class C
扩展到
Class B

我尝试的是:

class A(C):
    def __init__(self, driver):
        super().__init__(driver)

    class B:
        def __init__(self, *args, n=3):
            self.somethingA = args[0]
            self.somethingB = args[1]
但这是错误的。我有什么办法可以克服这个问题吗? 解决方案:
A.B(arg0,arg1)

什么是接近它的“正确”方式在很大程度上取决于驱动程序对象是什么。一种方法是将“driver”作为类变量设置为,然后根据需要进行设置。下面的代码将它设置为init,但是如果您需要更新它,那么您也可以有一个更新方法(可能也会使用C,但我不知道您的上下文)


B
不是
a
的子级。根据缩进,不清楚它是在
A中定义的。uuu init_uuu
还是在类
A
中定义为嵌套类。
A
没有属性
driver
;只有
A
的实例可以执行,这意味着您必须将
A
的实例传递给
B。请注意,嵌套类定义在Python中很少见。@chepner-ohk;我可以用这个片段把
A
的实例传递给
B.uu init_uu
@Prashanth
A.B(arg0,arg1,A(驱动程序))
。尽管如此,也许有更好的方法,但这取决于你想完成什么。@wjandrea感谢你的解决方案;是的,这是可行的,但我想要另一种方式;简化得多:)谢谢你@andrew;我试试这个。顺便说一句,我这里有类似的问题,我正在寻找一些替代建议来处理它
class A(C):
    def __init__(self, driver):
        super().__init__(driver)

    class B:
        def __init__(self, *args, n=3):
            self.somethingA = args[0]
            self.somethingB = args[1]
            self.driver = A.driver
class C(object):
    def __init__(self, driver):
        self.driver = driver

class A(C):
    driver = None
    
    def _set_driver_at_init(self, driver_at_init):
        driver = driver_at_init

    def __init__(self, driver):
        super().__init__(driver)
        self._set_driver_at_init(driver)

    class B:
        def __init__(self, *args, n=3):
            self.somethingA = args[0]
            self.somethingB = args[1]
            self.driver = A.driver