Python使用其他类的方法

Python使用其他类的方法,第1张

Python使用其他类的方法

有两种选择:

  • 在您的类中实例化一个对象,然后在其上调用所需的方法
  • 使用@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):    passB().a1() # => prints 'Hello from Superclass'


欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/zaji/5645203.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存