简体   繁体   中英

How to inherit all class attributes, but one? Python

How to inherit all class 'A' attributes and methods, but 'b()'?

class A:
    def __init__(self):
        #  attributes
        pass

    @classmethod
    def b(cls):
        #  logic
        pass


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

    def b(self):
        #  nothing
        pass

do not use this old method( if there is another way to do it ):

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

You can reimplement b() to raise an error:

class A:
    def __init__(self):
        #  attributes
        pass

    @classmethod
    def b(cls):
        #  logic
        pass


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

    @classmethod
    def b(cls):
        raise TypeError("method b is not supported in class B")

Also, if b() is a classmethod , you should probably override it as a classmethod .

Put that method in a separate class and don't inherit it.

class A:
    def __init__(self):
        #  attributes
        pass

class A1:
    @classmethod
    def b(cls):
        #  logic
        pass

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

Use multiple inheritance when you want that method.

class C(A,A1):
    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