0

How do I get attributes from parent class constructor in child class constructor?

class A:
    def __init__(number):
        self.number = number

class B(A):
    def __init__():
        self.number = A.number?

test = B(A)
print(test.number)

I don't know how to do it so as not to pass arguments to the child class.

  • You say you don't want "pass arguments to the child class." Do you actually want to pass the arguments to the parent class? – doctorlove Dec 19 '22 at 17:33
  • @doctorlove, yes, i don't like pass arguments to the child class, looks like this: test_two = B(number) – LeetCrash Dec 19 '22 at 17:36
  • Maybe see https://stackoverflow.com/questions/19205916/how-to-call-base-classs-init-method-from-the-child-class – doctorlove Dec 19 '22 at 17:39

1 Answers1

0

I think you have something wrong there. The correct code for parent / derived class would be

class A:
    def __init__(self, number):
        self.number = number

class B(A):
    def __init__(self, number):
        super().__init__(0) # Initialize parent class.
        self.number = number

# Instantiate a B object
test = B(7)
# Print the property
print(test.number)

That will always produce '7' in the screen. Now both A and B __init__ methods refer to the same 'number' property of the object, so, it does not make much sense both classes setting the same property upon initialization. If you change B's __init__ method for:

class B(A):
    def __init__(self, number):
        self.number = number
        super().__init__(0) # Initialize parent class.

Then print(test.number) would always print '0' instead of anything you passed on creation because you are overwriting the property.

The typical code would rather be:

class A:
    def __init__(self, number):
        self.number = number

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

This way the derived class initializes the parent in a meaningful way.

Juando
  • 1