Python使用其他类的方法

46 投票
3 回答
72218 浏览
提问于 2025-04-15 22:30

如果我有两个类,其中一个类里有一个我想在另一个类中使用的函数,我该怎么做才能不重复写这个函数呢?

3 个回答

7

你可以创建一个类,然后让其他两个类从这个类继承。

这里有多重继承的概念,所以如果它们已经有一个父类,那也没关系。

class master ():
    def stuff (self):
        pass

class first (master):
    pass


class second (master):
    pass


ichi=first()
ni=second()

ichi.stuff()
ni.stuff()
31

有几种方法可以实现这个功能:

  • 继承
  • 委托
  • 超级隐秘的委托

下面的例子展示了如何通过这几种方法共享一个打印成员的函数。

继承

class Common(object):
    def __init__(self,x):
        self.x = x
    def sharedMethod(self):
        print self.x

class Alpha(Common):
    def __init__(self):
        Common.__init__(self,"Alpha")

class Bravo(Common):
    def __init__(self):
        Common.__init__(self,"Bravo")

委托

class Common(object):
    def __init__(self,x):
        self.x = x
    def sharedMethod(self):
        print self.x

class Alpha(object):
    def __init__(self):
         self.common = Common("Alpha")
    def sharedMethod(self):
         self.common.sharedMethod()

class Bravo(object):
    def __init__(self):
         self.common = Common("Bravo")
    def sharedMethod(self):
         self.common.sharedMethod()

超级隐秘的委托
这个方法的基础是,Python 的成员函数并没有什么特别之处;只要第一个参数被解释为类的实例,你可以使用任何函数或可调用对象。

def commonPrint(self):
    print self.x

class Alpha(object):
    def __init__(self):
        self.x = "Alpha"
    sharedMethod = commonPrint

class Bravo(object):
    def __init__(self):
        self.x = "Bravo"
    sharedMethod = commonPrint

另外,一种同样隐秘的实现委托的方法是使用一个可调用对象:

class Printable(object):
   def __init__(self,x):
       self.x = x
   def __call__(self):
       print self.x

class Alpha(object):
   def __init__(self):
       self.sharedMethod = Printable("Alpha")

class Bravo(object):
   def __init__(self):
       self.sharedMethod = Printable("Bravo")
44

这里有两个选择:

  • 在你的类里面创建一个对象,然后调用你想要的方法。
  • 使用 @classmethod 把一个函数变成类的方法。

举个例子:

class A(object):
    def a1(self):
        """ This is an instance method. """
        print "Hello from an instance of A"

    @classmethod
    def a2(cls):
        """ This a classmethod. """
        print "Hello from class A"

class B(object):
    def b1(self):
        print A().a1() # => prints 'Hello from an instance of A'
        print A.a2() # => 'Hello from class A'

或者,如果合适的话,可以使用继承:

class A(object):
    def a1(self):
        print "Hello from Superclass"

class B(A):
    pass

B().a1() # => prints 'Hello from Superclass'

撰写回答