简体   繁体   中英

How to inherit every class in python?

I'm working with classes that have a lot of instance variables, and I want to have classes that inherit every instance variables from them. something like this:

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

obviously this won't work, but all the documentation that I can find on line is confusing. How do you inherit variables in cases like this?

Currently, your code is invalid syntax as a digit cannot be at the very front of a variable name. However, you can use *args with __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)

Output:

0
13

Use this as a template for your inheritance, emphasis on the super() method:

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

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

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

For your specific type of class (that takes an unknown number of initialization arguments, ie *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'

Now I would personally use the **kwargs over *args for specifying unique instance attributes:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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