时间:2021-07-01 10:21:17 帮助过:61人阅读
代码如下:
class Dog < Struct.new(:name, :age)
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