如何确定实例方法的对应类?

时间:2019-05-10 07:06:01

标签: python class methods attributes

例如,我有以下代码(新样式类):

class B:
    def func(self):
        # do something to instance of type B
        pass

class A:
   def __init__(self, random_variable):
       if random_variable > 0:
           self.func = B().func
       else:
           pass

   def func(self):
       # do something to instance of type A
       pass

a = A(random_variable)

如何确定实例func的{​​{1}}属性是最初绑定到B还是绑定到A而不检查随机变量的值?

1 个答案:

答案 0 :(得分:1)

请参考方法的__self__属性,该属性存储了它绑定到的实例,然后使用isinstance

baby = A(np.random.rand() - 0.5).func
if isinstance(baby.__self__, A):
    print("It's an A! Congratulations!")

elif isinstance(baby.__self__, B):
    print("It's a B...")

else:
    print("What...is this...?")

严格来说,我会指出,func最初总是绑定到A.func,因为您在__init__中对其进行了修改。