如何区分函数和类方法? [英] How to distinguish between a function and a class method?

查看:133
本文介绍了如何区分函数和类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果变量引用的是函数或类方法,那么如果它是类方法,尤其是在如给定示例中仍声明类的情况下,我如何找出它是哪个并获得类类型

If a variable refers to either a function or a class method, how can I find out which one it is and get the class type in case it is a class method especially when the class is still being declared as in the given example.

例如

def get_info(function_or_method):
    print function_or_method

class Foo(object):
    def __init__(self):
        pass

    get_info(__init__)

def bar():
    pass

get_info(bar)

在David和J. F. Sebastian的前两个回答之后更新至问题 为了再次强调J.F. Sebastian所提到的一点,我希望能够在类中声明该函数时(当我得到的类型是一个函数而不是绑定或未绑定的方法时)进行区分. IE.我希望能够在第一次调用get_info(__init__)的地方检测到它的方法被声明为类的一部分.

Update to question after the first two responses from David and J. F. Sebastian To reemphasize a point which J.F. Sebastian alluded to, I want to be able to distinguish it when the function is being declared within the class (when the type I am getting is a function and not a bound or unbound method). ie. where the first call to get_info(__init__) happens I would like to be able to detect that its a method being declared as a part of a class.

出现此问题是因为我在其周围放置了一个装饰器,并且该装饰器获得了 init 函数的句柄,而我实际上无法弄清是否在类中声明了一个方法或将其声明为独立功能

This question came up since I am putting a decorator around it and it gets a handle to the init function and I can't actually figure out if a method is being declared within a class or as a stand alone function

推荐答案

为了再次强调J.F. Sebastian提到的一点,我希望能够在类中声明函数时(当我得到的类型是函数而不是绑定或未绑定的方法时)进行区分. IE.我希望能够检测到第一次调用get_info(__init__)的地方,该方法被声明为类的一部分.

To reemphasize a point which J.F. Sebastian alluded to, I want to be able to distinguish it when the function is being declared within the class (when the type I am getting is a function and not a bound or unbound method). ie. where the first call to get_info(__init__) happens I would like to be able to detect that its a method being declared as a part of a class.

这个问题出现了,因为我在它周围放置了一个装饰器,并且它获得了init函数的句柄,而我实际上无法弄清楚是在类中还是作为独立函数声明了方法

This question came up since I am putting a decorator around it and it gets a handle to the init function and I can't actually figure out if a method is being declared within a class or as a stand alone function

不能.塞巴斯蒂安(J.F. Sebastian)的答案仍然是100%适用.当执行类定义的主体时,该类本身尚不存在.语句(__init__函数定义和get_info(__init__)调用)发生在新的本地名称空间中;在get_info调用发生时,__init__是对该名称空间中函数的引用,这与在类外部定义的函数没有区别.

You can't. J.F. Sebastian's answer is still 100% applicable. When the body of the class definition is being executed, the class itself doesn't exist yet. The statements (the __init__ function definition, and the get_info(__init__) call) happen in a new local namespace; at the time the call to get_info occurs, __init__ is a reference to the function in that namespace, which is indistinguishable from a function defined outside of a class.

这篇关于如何区分函数和类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆