Python 使用其他类的方法 [英] Python using methods from other classes

查看:20
本文介绍了Python 使用其他类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个类,其中一个类有一个我想在另一个类中使用的函数,我应该用什么来避免重写我的函数?

If I have two classes, and one of them has a function that I want to use in my other class, what do I use so that I don't have to rewrite my function?

推荐答案

有两个选项:

  • 在类中实例化一个对象,然后在其上调用所需的方法
  • 使用 @classmethod 将函数变成类方法
  • instanciate an object in your class, then call the desired method on it
  • use @classmethod to turn a function into a class method

示例:

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'

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

Or use inheritance, if appropriate:

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

class B(A):
    pass

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

这篇关于Python 使用其他类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆