【问题标题】:How to access the parent class during initialisation in python?如何在python初始化期间访问父类?
【发布时间】:2010-10-31 17:11:17
【问题描述】:

如何找出我在哪个类中初始化装饰器?由于装饰器尚未绑定到该类,因此我无法找到这一点是有道理的,但是有没有办法解决这个问题?

class A(object):
    def dec(f):
                # I am in class 'A'
        def func(cls):
            f(cls)
        return func

    @dec
    def test(self):
        pass

我需要知道我是哪个班级(由注释行表示)。

【问题讨论】:

  • 问题 805066 是关于 super() 的,我看不出这有什么帮助。
  • 正如您的示例所代表的那样,无法绕过它。但是,如果您详细说明为什么需要访问该课程,我们可以帮助您找到更好的方法。

标签: python decorator introspection


【解决方案1】:

我认为这是不可能的。在你定义 test 的那一刻,这个类还不存在。

当Python遇到

class A(object):

它创建一个新的命名空间,在其中运行它在类定义中找到的所有代码(包括 test() 的定义和对装饰器的调用),完成后,它创建一个新的类对象并将代码执行后留在命名空间中的所有内容。

所以当装饰器被调用时,它还不知道任何东西。此时,测试只是一个函数。

【讨论】:

    【解决方案2】:

    我不明白这个问题。

    >>> class A(object):
        def dec(f):
            def func(cls):
                print cls
            return func
    
        @dec
        def test(self):
            pass
    
    >>> a=A()
    >>> a.test()
    <__main__.A object at 0x00C56330>
    >>> 
    

    参数 (cls) 是类,A

    【讨论】:

    • 他想知道 func 的定义之前(无论出于何种原因)。
    • 由于似乎不需要知道“在”类定义之前,我不明白这个问题。
    【解决方案3】:

    正如 Nadia 指出的那样,您需要更加具体。 Python 不允许这种事情,这意味着你正在尝试做的事情可能是错误的。

    同时,这是我的贡献:一个关于水手和青蛙的小故事。 (在类初始化之后使用构造函数

    class Cruise(object):
        def arewelostyet(self):
            print 'Young sailor: I think I am lost, help me :s'
    
    instance = Cruise()
    
    instance.arewelostyet()
    
    def whereami(lostfunc):
        """
        decorator
        """
        def decorated(*args, **kwargs):
            lostfunc(*args, **kwargs)
            print 'Frog: Crôak! thou art sailing in class', lostfunc.im_class.__name__
    
        # don't forget to write name and doc
        decorated.func_name = lostfunc.func_name
        decorated.func_doc = lostfunc.func_name
    
        return decorated
    
    
    print '[i]A frog pops out of nowhere[/i]'
    
    # decorate the method:
    Cruise.arewelostyet = whereami(Cruise.arewelostyet)
    
    instance.arewelostyet()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-05
      • 1970-01-01
      相关资源
      最近更新 更多