首页 > 解决方案 > 识别python中的函数

问题描述

我正在尝试使用“ast”解析 python 文件,并且我能够成功地做到这一点。

现在我需要区分'dict'和'list'的默认方法

示例:
我可以有如下方法

classa = new TestClassA
classa.test()

但是如果我调用“dict”/“list”的方法

some_dict = dict() 
some_dict.keys()

我需要识别'dict'和'list'的默认方法并跳过它

一种方法是:我可以拥有配置文件中的所有方法,我可以跳过它,但如果有更好的识别方法,请告诉我。

标签: pythonabstract-syntax-tree

解决方案


您可以通过两种简单的方式了解给定对象的方法和属性:

  1. dir()在对象或对象实例上使用函数
  2. 使用help()功能

1. dir() 函数

>>> d = dict()
>>> type(d)
<class 'dict'>
>>> for attribute in dir(d):
...   print(attribute)
... 
__gt__
clear
copy
fromkeys
get
items
keys
pop
popitem
setdefault
update
values

2. help() 函数

这可能是打印对象的属性和功能的最优雅的方式

class dict(object)
 |  dict() -> new empty dictionary
 |  dict(mapping) -> new dictionary initialized from a mapping object's
 |      (key, value) pairs
 |  dict(iterable) -> new dictionary initialized as if via:
 |      d = {}
 |      for k, v in iterable:
 |          d[k] = v
 |  dict(**kwargs) -> new dictionary initialized with the name=value pairs
 |      in the keyword argument list.  For example:  dict(one=1, two=2)
 |  
 |  Methods defined here:
 |  
 |  __contains__(self, key, /)
 |      True if D has a key k, else False.
 |  
 |  __delitem__(self, key, /)
 |      Delete self[key].
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 ...
 ...
 |  copy(...)
 |      D.copy() -> a shallow copy of D
 |  
 |  fromkeys(iterable, value=None, /) from builtins.type
 |      Returns a new dict with keys from iterable and values equal to value.
 |  
 |  get(...)
 |      D.get(k[,d]) -> D[k] if k in D, else d.  d defaults to None.
 |  
 |  items(...)
 |      D.items() -> a set-like object providing a view on D's items
 |  
 |  keys(...)
 |      D.keys() -> a set-like object providing a view on D's keys
 |  
 |  pop(...)
 |      D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
 |      If key is not found, d is returned if given, otherwise KeyError is raised
 |  
 |  popitem(...)
 |      D.popitem() -> (k, v), remove and return some (key, value) pair as a
 |      2-tuple; but raise KeyError if D is empty.
 |  
 |  setdefault(...)
 |      D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
 |  
 |  update(...)
 |      D.update([E, ]**F) -> None.  Update D from dict/iterable E and F.
 |      If E is present and has a .keys() method, then does:  for k in E: D[k] = E[k]
 |      If E is present and lacks a .keys() method, then does:  for k, v in E: D[k] = v
 |      In either case, this is followed by: for k in F:  D[k] = F[k]
 |  
 |  values(...)
 |      D.values() -> an object providing a view on D's values
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None

推荐阅读