有没有类似 dir(obj)的方法,可以查看 obj 的全部属性和法,但要将属性和方法区分开?

2017-06-16 09:50:04 +08:00
 vtoexsir

比如有如下的类(当然只定义方法也是可以的):

class A():
	a = '这是属性'

	def d(self, var):
    	print('这是方法')

	def dd(self):
   		print('这是没有参数的方法')

	aa = dd  #也算属性吧

print(dir(A))
# =>['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'a', 'aa', 'd', 'dd']

dir(obj),虽然能获得['a', 'aa', 'd', 'dd'] ,但是不能区分是方法还是属性。
有什么方法或者现成的库可以将方法和属性分开呢?
多谢您回复!

2033 次点击
所在节点    Python
7 条回复
XYxe
2017-06-16 10:22:20 +08:00
guyskk
2017-06-16 10:38:06 +08:00
Python 里方法就是可调用的属性,上面的 aa 和 dd 是完全一样的,没法区分。a 和 d 可以用 getattr 取出来在判断是不是 callable 区分。
congeec
2017-06-16 11:40:42 +08:00
注意一下 @property
NoAnyLove
2017-06-16 11:42:18 +08:00
`aa`应该算作 function 了。另外,`inspect`模块也可以用:

```
>>> import inspect
>>> inspect.getmembers(A, inspect.isfunction)
[('aa', <function __main__.A.dd>),
('d', <function __main__.A.d>),
('dd', <function __main__.A.dd>)]
```

```
>>> inspect.getmembers(A, lambda x: not callable(x))
[('__dict__',
mappingproxy({'__dict__': <attribute '__dict__' of 'A' objects>,
'__doc__': None,
'__module__': '__main__',
'__weakref__': <attribute '__weakref__' of 'A' objects>,
'a': '这是属性',
'aa': <function __main__.A.dd>,
'd': <function __main__.A.d>,
'dd': <function __main__.A.dd>})),
('__doc__', None),
('__module__', '__main__'),
('__weakref__', <attribute '__weakref__' of 'A' objects>),
('a', '这是属性')]
```
vtoexsir
2017-06-16 20:35:04 +08:00
非常感谢各位!
pdir 内部也是调用 inspect。
谢谢!
mingyun
2017-06-17 00:15:58 +08:00
@XYxe nice
yucongo
2017-06-17 15:51:13 +08:00
pdir2 不错,感谢一下 XYxe。也感谢一下提问者,我也在有过同样的疑问,比如 pathlib 里的 Path 不知道哪个是属性、哪个是方法……

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/368778

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX