有没有办法在不同的类之间共享def?

2024-04-20 06:37:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个相当多的类的应用程序。根据def的定义,这些类有许多函数是公共的,显然有些不是。你知道吗

有没有一种方法可以定义在一个地方有公共函数并可用于许多类的函数,或者每个类中都必须至少有def?你知道吗


Tags: 方法函数应用程序定义def地方
2条回答

正如Amadan在评论中指出的,类继承是共享类对象的一种良好且一致的方式。下面是一个例子:

class animals:

    def __init__(self):
        pass

    def has_legs(self, type):
        if type == "snake":
            print(False)
        else:
            print(True)


class dog(animals):

    def __init__(self):
        # This is where the magic happens
        animals.__init__(self)
        pass

    def dog_has_legs(self):
        self.has_legs("dog")


bofur = dog()
bofur.dog_has_legs()
bofur.has_legs("snake")

结果:

>>> bofur.dog_has_legs()
True
>>> bofur.has_legs("snake")
False

如您所见,类dog继承自animals,因此它可以从animals类调用函数和其他对象,就好像它们属于dog类一样。你知道吗

首先定义func,它在外部定义。
然后要在不同的类中引用该函数,请在类中使用相同的func

def func():
    print('func')

class B:

    def funcB(self):
        print('funcB')

    def func(self):
        func()

class C:

    def funcC(self):
        print('funcC')

    def func(self):
        func()

现在可以这样称呼它们。你知道吗

b = B()
b.func()
#funcA
b.funcB()
#funcB
c = C()
c.func()
#funcA
c.funcC()
#funcC

相关问题 更多 >