Home > other >  Purposely trying to break Python class inheritance, don't understand why it breaks this way
Purposely trying to break Python class inheritance, don't understand why it breaks this way

Time:04-04

I'm exploring the limits of Python class inheritance, so I wrote a small test to see how much I can get away with - redeclaring properties and overriding functions.

class A:
    val : int = 3
    def foo(x: int):
        print(x)

class B(A):
    val : str = 'python'
    def foo(x: str):
        print(x)

a = A()
b = B()
a.foo(5)
b.foo('test')
print(a.val)
print(b.val)

The resulting output is surprising. I would have expected some kind of exception for redeclaring the property, but instead I get:

Traceback (most recent call last):
  File "c:\Development\Playground\hello.py", line 12, in <module>
    a.foo(5)
TypeError: A.foo() takes 1 positional argument but 2 were given

I don't see how it interpreting that I am providing two positional arguments for a.foo(5). Granted I am trying to break it but I still want to understand.

CodePudding user response:

You need a self parameter for instance methods.

class A:
    val : int = 3
    def foo(self, x: int):
        print(x)

class B(A):
    val : str = 'python'
    def foo(self, x: str):
        print(x)

a = A()
b = B()
a.foo(5)
b.foo('test')
print(a.val)
print(b.val)

Output:

5
test
3
python

CodePudding user response:

I think the error is produced because self was automatically passed since it's a function of a class so your functions have to take self as their first argument

class A:
    val : int = 3
    def foo(self, x: int):
        print(x)

class B(A):
    val : str = 'python'
    def foo(self, x: str):
        print(x)
  • Related