gpt4 book ai didi

python - 识别python中的函数

转载 作者:太空宇宙 更新时间:2023-11-04 11:15:43 25 4
gpt4 key购买 nike

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

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

例子:
我可以有如下方法

classa = new TestClassA
classa.test()

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

some_dict = dict() 
some_dict.keys()

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

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

最佳答案

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

  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。帮助()函数

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

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

关于python - 识别python中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57042028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com