Python使用其他类的方法 [英] Python using methods from other classes
本文介绍了Python使用其他类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有两个类,其中一个类有一个我想在其他类中使用的函数,那我该怎么用,所以我不需要重写我的函数?
解决方案
有两个选项:
- ,然后调用所需的方法
- 使用 @ class方法将函数转换为类方法
示例:
$ b $$
这是一个实例方法。
print你从A的一个实例
@classmethod
def a2(cls):
这是一个类方法。
class B(object):
def b1(self):
print A()。a1()#=>从A'
print A.a2()#=>的实例打印Hello 'A级'你好'
或使用继承(如果适用):
class A(object):
def a1(self):
print你好从超类
B(A)类:
pass
B()。a1()#=>打印你好,超级类
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?
解决方案
There are two options:
- instanciate an object in your class, then call the desired method on it
- use @classmethod to turn a function into a class method
Example:
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屋!
查看全文