【问题标题】:Class out of class variable in PythonPython中的类外变量
【发布时间】:2015-11-10 12:02:29
【问题描述】:

有没有办法从类变量中获取类?

class T():
    x = 5
    y = 6

我的函数接受 T.x 作为参数,我也想获取 T.y。

【问题讨论】:

  • 从类变量中获取类是什么意思?
  • 不,您无法从值中分辨出哪个类引用了它。你的函数被传递给5,而不是T.x,这个整数对象并没有告诉你它有哪些引用。
  • 如果你问“当我打电话给some_function(T.x) 时,some_function 有没有办法确定类T,然后找到T.y?”,那么,没有。就some_function 而言,您传递给它的值是一个简单的整数,没有可跟踪的信息。
  • 嗯.. ast 模块呢?
  • @user1505497: 怎么样?您想要 a) 从sys._getframe() 获取调用者框架,然后 b) 获取该调用者框架的源代码,然后 c) 解析源代码,以便您可以尝试找出用于传递变量的表达式?由于 Python 的动态特性和灵活性,这有许多 缺陷。你的问题在细节上太细了,甚至无法开始追踪那个兔子洞。

标签: python class


【解决方案1】:

从技术上讲,您可以使用元类来做这样的事情:(Python 3):

class MetaT(type):
    def __new__(meta, name, bases, dct):
        for k in dct:
            #print("wrapping %s"%k)
            class Wrap(type(dct[k])):
                __parent_class__ = None
            dct[k] = Wrap(dct[k])
        return super(MetaT, meta).__new__(meta, name, bases, dct)

    def __init__(cls, name, bases, dct):
        for k in dct:
            dct[k].__parent_class__ = cls
        super(MetaT, cls).__init__(name, bases, dct)

class T(metaclass=MetaT):
    x = 8
    y = 9

def get_other_attribute(arg):
    print("I got passed", arg)
    print("The parent class is", arg.__parent_class__)
    print("So I can reach attribute y:", arg.__parent_class__.y)

get_other_attribute(T.x)

但是,这个 hack 不好,你不应该不要使用它,你必须重新审视你的设计。我只是为了学习一点 Python 知识,并证明它可以通过足够多的 hack 来完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-23
    • 2020-02-16
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    相关资源
    最近更新 更多