从被调用的函数访问Class属性?

时间:2020-07-29 03:31:05

标签: python-3.x class attributes inspect

假设我有这样的东西:

  --module1

  def called():
     if caller.class.attrX == 1 : ...

  --module2
  class ABC:
     attrX = 1
     def method():
        called()

我要访问呼叫者的Class-attribute吗?

我知道我必须以某种方式使用检查,但是可以准确地知道。 python3

2 个答案:

答案 0 :(得分:0)

将变量传递给函数是最好的(也是唯一的选择)。

 --module1

  def called(attrX):
     if attrX == 1 : ...

  --module2
  class ABC:
     self.attrX = 1
     def method():
        called(self.attrX)

答案 1 :(得分:0)

这似乎适用于对象变量: /如果我可以使其适用于class-var,那会更好/

import inspect

def say(*args, **kwargs) :

    obj = inspect.currentframe().f_back.f_locals['self']
    if hasattr(obj,'aaa') : print('hasit')
    else : print("no")


class ABC:
    aaa = 2

    def test(self):
        say(123)    

即如果我没有预先设置“ aaa”:

In [8]: a.test()                                                                                                                                                             
no

In [9]: ABC.aaa = 2                                                                                                                                                           

In [10]: a.test()                                                                                                                                                            
no


In [12]: a.aaa = 3                                                                                                                                                            

In [13]: a.test()                                                                                                                                                            
hasit
相关问题