相关疑难解决方法(0)

将方法应用于另一个类的对象

给定两个不相关的类A和B,如何A.method使用B的对象调用self

class A:
    def __init__(self, x):
        self.x = x

    def print_x(self):
        print self.x

class B:
    def __init__(self, x):
        self.x = x

a = A('spam')
b = B('eggs')

a.print_x() #<-- spam
<magic>(A.print_x, b) #<-- 'eggs'
Run Code Online (Sandbox Code Playgroud)

python

5
推荐指数
1
解决办法
1844
查看次数

标签 统计

python ×1