Pho*_*nix 1 python attributes types python-3.x
NewType=type('nt',(object,),{'x':'hello'})
n=NewType()
n.x
'hello'
Run Code Online (Sandbox Code Playgroud)
我怎样{'x':'hello'}从n 获得dict ?
尝试失败: n.__bases__, n.__dir__, n.__dict__
你有一个类属性,所以NewType.__dict__会工作.
替代路线将是:
type(n).__dict__
vars(NewType)
vars(type(n))
Run Code Online (Sandbox Code Playgroud)
演示:
>>> NewType=type('nt',(object,),{'x':'hello'})
>>> n=NewType()
>>> n.x
'hello'
>>> NewType.__dict__
dict_proxy({'__dict__': <attribute '__dict__' of 'nt' objects>, 'x': 'hello', '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'nt' objects>, '__doc__': None})
>>> type(n).__dict__
dict_proxy({'__dict__': <attribute '__dict__' of 'nt' objects>, 'x': 'hello', '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'nt' objects>, '__doc__': None})
>>> vars(NewType)
dict_proxy({'__dict__': <attribute '__dict__' of 'nt' objects>, 'x': 'hello', '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'nt' objects>, '__doc__': None})
>>> vars(type(n))
dict_proxy({'__dict__': <attribute '__dict__' of 'nt' objects>, 'x': 'hello', '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'nt' objects>, '__doc__': None})
Run Code Online (Sandbox Code Playgroud)
类字典中还有一些属性(包括__dict__它自己).
| 归档时间: |
|
| 查看次数: |
52 次 |
| 最近记录: |