简体   繁体   中英

Inherit attribute from class that is isn't passed into __init__ method

Ok, so let's say I'm making a class and a child class like this:

class A:
    def __init__(self, list1=[], list2=[]):
        self.list1 = []
        self.list2 = []

class B(A):
    def __init__(self, list2=[]):
       super().__init__(list2)

But, is there a way to implement it like this

class A:
    def __init__(self):
        self.list1 = []
        self.list2 = []

class B(A):
    # code here to inherit list1 or list2 from class A

Basically, a way to implement it so the user can't give a value for list1 and list2 (they'd be initialized as empty lists and the user can add elements later with some method) and have class B inherit a list from class A

I feel like there is a way to do this other than my workaround, but maybe not because it's a really specific problem

The code you provided already does what you want it to do.

class A:
    def __init__(self):
        self.list1 = []
        self.list2 = []

class B(A):
    pass

b = B()

print(b.list1)  # prints []

When you inherit a class, you inherit all of its methods, including __init__ . Therefore, A.__init__ is (implicitly) called when initializing B . It's roughly equivalent to

class A:
    def __init__(self):
        self.list1 = []
        self.list2 = []

class B(A):
    def __init__(self):
        super().__init__()

which means (almost) the same thing. You would never do this just to be more explicit; you would only do it if you wanted to add behavior to B.__init__ that A.__init__ shouldn't have.

Your code already does what you want:

class A:
    def __init__(self):
        self.list1 = []
        self.list2 = []

class B(A):
    # code here to inherit list1 or list2 from class A
    def __init__(self):
        super().__init__() # <- This calls class A init function which creates the two empty lists

Your code does nothing with the user-provided lists. I think you meant this:

class A:
    def __init__(self, list1=[], list2=[]):
        self.list1 = list1
        self.list2 = list2

class B(A):
    def __init__(self, list2=[]):
       super().__init__(list2=list2)

And if you want to inherit the lists in class B from class A, your code has to be as follows:

class A:
    def __init__(self):
        self.list1 = []
        self.list2 = []

class B(A):
    pass

And for modification of the lists, provide a setter function:

class A:
    def __init__(self):
        self.list1 = []
        self.list2 = []
    def set_list1(list):
        self.list1 = list
    def set_list2(list):
        self.list2 = list

class B(A):
    pass

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