이 당신이 원하는 것을 수행합니다 ^^
class Basket(object):
def __init__(self):
# add all the properties
def make_prop(name):
def getter(self):
return "I'm a " + name
return property(getter)
for p in self.PropNames():
setattr(Basket, p, make_prop(p))
def PropNames(self):
# The names of all the properties
return ['Apple', 'Pear', 'Bread']
# normal property
Air = property(lambda s : "I'm Air")
if __name__ == "__main__":
b = Basket()
print b.Air
print b.Apple
print b.Pear
그것이 메타 클래스 것 할 수있는 또 다른 방법을 ...하지만 그들은 많은 사람들을 혼란.
나는 지루 해요 때문에 : __init__
시간에
class WithProperties(type):
""" Converts `__props__` names to actual properties """
def __new__(cls, name, bases, attrs):
props = set(attrs.get('__props__',()))
for base in bases:
props |= set(getattr(base, '__props__',()))
def make_prop(name):
def getter(self):
return "I'm a " + name
return property(getter)
for prop in props:
attrs[ prop ] = make_prop(prop)
return super(WithProperties, cls).__new__(cls, name, bases, attrs)
class Basket(object):
__metaclass__ = WithProperties
__props__ = ['Apple', 'Pear']
Air = property(lambda s : "I'm Air")
class OtherBasket(Basket):
__props__ = ['Fish', 'Bread']
if __name__ == "__main__":
b = Basket()
print b.Air
print b.Apple
print b.Pear
c = OtherBasket()
print c.Air
print c.Apple
print c.Pear
print c.Fish
print c.Bread
을 할 필요는 없습니다
PropNames
prop_names
. 이것에 대한 메타 핸들은 너무 강력합니다. 왜냐하면 이것은 덜 강력한 수단을 사용하여 수행 할 수 있기 때문입니다. –업데이트 해 주셔서 감사합니다. 사실 파이썬에서 메타 클래스만큼 깊게 들어간 적이 없었습니다. 어쩌면 이것이 그들에 대한 독서를 시작할 좋은 이유 일 것입니다. – pkit