繁体   English   中英

如何继承python中的每个类?

[英]How to inherit every class in python?

我正在使用具有很多实例变量的类,并且我想拥有从它们继承每个实例变量的类。 像这样的东西:

class foo(object):
    def __init__(self,thing1,thing2,thing3,thing4,thing5,thingetc):
        self.1 = thing1
        self.2 = thing2
        self.3 = thing3
        self.4 = thing4
        self.5 = thing5
        self.etc = thingetc

class bar(foo):
    self.6 = []
a = bar
print a.3

显然,这是行不通的,但是我在网上可以找到的所有文档都很混乱。 在这种情况下如何继承变量?

当前,您的代码是无效的语法,因为数字不能位于变量名的最前面。 但是,可以将*args__dict__

class foo:
  def __init__(self, *args):
     self.__dict__ = dict(zip(['var{}'.format(i) for i in range(1, len(args)+1)], args))

f = foo(*range(15))
print(f.var1)
print(f.var14)

输出:

0
13

使用它作为继承模板,重点是super()方法:

class Foo:
    def __init__(self):
        self.name = 'Foo'

class Bar(Foo):
    def __init__(self):
        super().__init__()

b = Bar()
b.name
# outputs 'Foo'

对于您的特定类型的类(需要未知数量的初始化参数,即* args ):

class Foo:
    def __init__(self, *args):
        self.name = 'Foo'
        for i, arg in enumerate(args):
            setattr(self, 'thing_' + str(i), arg)

class Bar(Foo):
    def __init__(self, *args):
        super().__init__(*args)

b = Bar('hello', 'world')
b.name
# outputs 'Foo'
b.thing_0
# outputs 'hello'
b.thing_1
# outputs 'world'

现在,我将使用*args**kwargs来指定唯一的实例属性:

class Foo:
    def __init__(self, **kwargs):
        self.name = 'Foo'
        for att in kwargs:
            setattr(self, att, kwargs[att])

class Bar(Foo):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

b = Bar(value = 4, area = 3.14)
b.name
# outputs 'Foo'
b.value
# outputs 4
b.area
# outputs 3.14

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM