Home > Article > Backend Development > Python中使用装饰器和元编程实现结构体类实例
Ruby中有一个很方便的Struct类,用来实现结构体。这样就不用费力的去定义一个完整的类来仅仅用作访问属性。
代码如下:
class Dog
end
fred = Dog.new("fred", 5)
printf "name:%s age:%d", fred.name, fred.age
##name:fred age:5
代码如下:
class Dog(object):
def __init__(self, name, age):
self.name = name
self.age = age
fred = Dog("fred", 5)
print('name:{name} age:{age}'.format(name=fred.name, age=fred.age))
##name:fred age:5
代码如下:
def struct(*name):
""" 装饰器函数
用途:用于在类定义中,自动设置self.value = value
"""
def decorator(func):
def wrapper(*args, **kw):
for i in range(len(name)):
setattr(args[0], name[i], args[i+1])
return func(*args, **kw)
return wrapper
return decorator
class Dog(object):
@struct('name','age') #黑魔法所在!
def __init__(self, *all_value):
pass
fred = Dog("fred", 5)
print('name:{name} age:{age}'.format(name=fred.name, age=fred.age))
##name:fred age:5