Python 支持“动态”创建属性,就像这样。
class MyClass:
def __init__(self):
pass
x = MyClass
x.new = 5
print(x.new) # prints 5
Run Code Online (Sandbox Code Playgroud)
但这有点难看。我必须在类中有一些指令,函数或类属性定义。
但主要的障碍是...
x.first.second = 1 # this will raise
Run Code Online (Sandbox Code Playgroud)
它提高是因为 first 显然不存在。我将不得不做这样的事情。
x.first = MyClass()
x.first.second = 1
print(x.first.second)
Run Code Online (Sandbox Code Playgroud)
我想根据需要递归创建属性。这可能吗?
使用__getattr__创建一个新的属性命名空间和回报。__eq__被执行。行为类似于types.SimpleNamespace。
class Namespace:
def __init__(self):
pass
def __getattr__(self, item):
ret = Namespace()
setattr(self, item, ret)
return ret
def __eq__(self, other):
return isinstance(other, Namespace) and vars(self) == vars(other)
ns = Namespace()
ns.first.second = 1
print(ns.first.second) # 1
Run Code Online (Sandbox Code Playgroud)
然而,这有副作用
print(ns.unknown) # <__main__.Namespace object at 0x0000025FC1E5B400>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
132 次 |
| 最近记录: |