Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

python - 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

question from:https://stackoverflow.com/questions/65545455/inherit-attribute-from-class-that-is-isnt-passed-into-init-method

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...