我正在尝试使用'ast'解析python文件,并且能够成功完成。
现在我需要区分默认方法“ dict”和“ list”
示例:
我可以使用下面的方法
classa = new TestClassA
classa.test()
但是如果我调用'dict'/'list'方法
some_dict = dict()
some_dict.keys()
我需要确定'dict'和'list'的默认方法并跳过它
一种方法是:我可以在配置文件中包含所有方法,并且可以跳过它,但是如果有更好的标识方法,请告诉我。
答案 0 :(得分:2)
您可以通过两种简单的方法来了解给定对象的方法和属性:
dir()
函数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
答案 1 :(得分:1)
您可以通过调用__init__
获得由类定义的成员列表。因此,例如BaseClass
和dir(class_name)
将提供这两个类中每个类的所有成员。请注意,这包括特殊名称,例如dir(list)
以及字段。您仍然必须确定您实际要跳过哪些。