z7s*_*g Ѫ 1 python class object
考虑到内存使用,时钟周期或良好的pythonic风格,最好这样做:
def func():
class A:
x = 10
y = 20
return A
Run Code Online (Sandbox Code Playgroud)
或这个
def func():
o = object()
o.x = 10
o.y = 20
return o
Run Code Online (Sandbox Code Playgroud)
或者是其他东西?我不想返回字典,因为我不喜欢使用方括号.
我喜欢使用一种特殊的方法来制作dict我在这里找到的子类.看起来像:
class Struct(dict):
"""Python Objects that act like Javascript Objects"""
def __init__(self, *args, **kwargs):
super(Struct, self).__init__(*args, **kwargs)
self.__dict__ = self
Run Code Online (Sandbox Code Playgroud)
这个对象可以这样使用:
o = Struct(x=10)
o.y = 20
o['z'] = 30
print o.x, o['y'], o.z
Run Code Online (Sandbox Code Playgroud)
可以以可交换的方式使用不同类型的访问.