最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Python中如果获得一个变量的所有的域值/成员变量/属性值,以及所有的方法/函数

Python crifan 3300浏览 0评论

【问题】

在Python中,已得到一个cookie,是cookielib.Cookie类型的变量。

想要获得该变量的所有的域值,即成员变量,同时最好也能获得对应的变量具有哪些函数/方法。

记得之前好像看到有人写帖子,介绍如何获得的,但是忘了具体的代码了。

【解决过程】

1.在 第11章 面向对象的编程 中,看到有提到__init__。

然后去python 2.7自动的帮助文档中,搜索__init__,然后后来就找到了__members__:

object.__members__

Deprecated since version 2.2: Use the built-in function dir() to get a list of an object’s attributes. This attribute is no longer available.

2. 也在这里 [转载]Python的特点 看到了dir()函数,好像可以得到我要的效果。

 

3.后来就去测试了相关的很多个这些特殊的内置变量或函数的效果,代码如下:

print "follow cookie is a cookielib.Cookie object/variable, now do test:";
print cookie.__class__; # cookielib.Cookie
print cookie.__dict__; # {'comment': None, 'domain': '.baidu.com', 'name': 'BAIDUID', 'domain_initial_dot': True, 'expires': 2277364152L, 'value': '663B7080AD888D30F71D3558C709AB9A:FG=1', 'domain_specified': True, '_t_specified': False, 'rfc2109': False, 'discard': False, 'path_specified': True, 'path': '/', 'port': None, 'comment_url': None, 'secure': False}
#print cookie.__members__; # Deprecated since version 2.2 -> dir()
#print cookie.__methods__; # Deprecated since version 2.2 -> dir()
print dir(cookie); # ['__doc__', '__init__', '__module__', '__repr__', '__str__', '_rest', 'comment', 'comment_url', 'discard', 'domain', 'domain_initial_dot', 'domain_specified', 'expires', 'get_nonstandard_attrs_expired', 'name', 'path', 'path_specified', 'port', 'port_specified', 'rfc2109', 'secure', 'set_nonstandard_attr', 'value', 'version']

 

【总结】

想要获得一个变量variable的所有的域值/成员/属性,可以通过dir(variable)来获得。

相关的变量或函数还有:object.__dict__ , instance.__class__,等等。

转载请注明:在路上 » 【已解决】Python中如果获得一个变量的所有的域值/成员变量/属性值,以及所有的方法/函数

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.164 seconds, using 22.18MB memory