简体   繁体   中英

Extending a built-in function in Python proper syntax?

class EvenOnly(list):
    def append(self, integer):
        if not isinstance(integer, int):
            raise TypeError(f"'{integer}' is not an integer.")
        if integer % 2:
            raise ValueError(f"'{integer}' is not an even integer")
        super().append(integer)

Notice the "super()" call at the end of the code. If I change it to "list.append(integer)" which, from my understanding, just specifies the parent class it is calling to (similar to multi inheritance), it provides this error when executing:

TypeError: descriptor 'append' for 'list' objects doesn't apply to a 'int' object

Why is that? I understand that it's unnecessary to specify the parent class in this case, but I wonder what's making the difference that causes an error.

The equivalent of

super().append(integer)

in your particular context would be

list.append(self, integer)

Since list is a type, you need to explicitly specify the list as well. list.append is a function object, whereas self.append is a bound method object . One takes two arguments and the other takes one.

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