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

查看:110
本文介绍了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'

或者使用继承:

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

class B(A):
    pass

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

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

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