Найти - Пользователи
Полная версия: inspect.ismethod
Начало » Python для новичков » inspect.ismethod
1 2
Budulianin
Всем привет

Хочу уточнить по поводу inspect.ismethod()

Эта функция выводит True, только для методов, которые описаны в классах ?

Например

import inspect
class Test(object):
    def test(self):
        pass
l = [123]
print inspect.ismethod(Test.test), type(Test.test)
print inspect.ismethod(l.append), type(l.append)
—————–
True <type ‘instancemethod’>
False <type ‘builtin_function_or_method’>
lorien
А какие ещё методы бывают?
Budulianin
lorien
А какие ещё методы бывают?
Я имел в виду классы, которые сам описал. Мне непонятно, почему у

print inspect.ismethod(l.append), type(l.append)

выводит

False <type ‘builtin_function_or_method’>

это ведь тоже метод
buddha
Начал было писать своими словами, но написал некорректно. Потому просто предлагаю посмотреть в реализацию метода inspect.ismethod():

import inspect
 
#отсюда видно, что это лишь обёртка для встроенной функции isinstance()
def ismethod(object):
    """Return true if the object is an instance method.
  
    Instance method objects provide these attributes:
        __doc__         documentation string
        __name__        name with which this method was defined
        __func__        function object containing implementation of method
        __self__        instance to which this method is bound"""
    return isinstance(object, types.MethodType)
 
# но что такое types.MethodType ? смотрим в модуль types:
class _C:
    def _m(self): pass
  
MethodType = type(_C()._m)
 
# странно то, что для выражения inspect.ismethod(l.append) возвращается False! смотрим дальше:
l = [1, 2, 3]
print(type(l.append)) # <class 'builtin_function_or_method'>
  
# смотрим в модуль types:
BuiltinFunctionType = type(len)
BuiltinMethodType = type([].append)     # Same as BuiltinFunctionType
  
# смотрим в модуль inspect, какой же метод работает с этими типами:
def isbuiltin(object):
    """Return true if the object is a built-in function or method.
  
    Built-in functions and methods provide these attributes:
        __doc__         documentation string
        __name__        original name of this function or method
        __self__        instance to which a method is bound, or None"""
    return isinstance(object, types.BuiltinFunctionType)
  
# пробуем:
print(inspect.isbuiltin(l.append)) # True
Budulianin
buddha, спасибо за столь развёрнутый ответ, теперь понятно


Непонятно только почему в Python у type(len) и type(.append) один тип

Получается, нельзя различить тип len от типа .append, или всё таки, как-то можно ?
buddha
На этот счёт идей нету. Т.к. и функция и метод встроенные, я б не парился на этот счёт.

>>> import types
>>> isinstance(len, types.BuiltinFunctionType)
True
>>> isinstance(len, types.BuiltinMethodType)
True
>>> isinstance([].append, types.BuiltinMethodType)
True
>>> isinstance([].append, types.BuiltinFunctionType)
True
Shaman
А в документации всё четко написано:
inspect.ismethod(object)
Return true if the object is a bound method written in Python.

Budulianin
Shaman
А в документации всё четко написано:inspect.ismethod(object) Return true if the object is a bound method written in Python.

class A:
     def func(self):
         pass
>>> A.func
<unbound method A.func>
>>> a = A()
>>> a.func
<bound method ...>
>>>inspect.ismethod(A.func)
True
>>>inspect.ismethod(a.func)
True

Return true if the object is a bound method

И в чём прикол?

Связанность\несвязанность метода не влияет, inspect.ismethod выводит True, если <type ‘instancemethod’>, а у связанного и несвязанного метода один тип. В документации ошибка ?
Shaman
Budulianin
И в чём прикол?
Вот в чем
def ismethod(object):
    """Return true if the object is an instance method.
    Instance method objects provide these attributes:
        __doc__         documentation string
        __name__        name with which this method was defined
        im_class        class object in which this method belongs
        im_func         function object containing implementation of method
        im_self         instance to which this method is bound, or None"""
    return isinstance(object, types.MethodType)
types.py
UnboundMethodType = type(_C._m)         # Same as MethodType
_x = _C()
MethodType = type(_x._m)
Документация
types.MethodType
The type of methods of user-defined class instances.

types.UnboundMethodType
An alternate name for MethodType.
В документации видимо не отражены текущие изменения, но я ударение делал на “писанные на Питоне”.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB