這確實想要的東西:
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
另一種方式來做到這將是一個元類......但他們迷惑了很多人^^。
因爲我很無聊:
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
我不同意,正確的方式做這將是一個元類。元類對於這個來說太強大了,因爲這可以使用不那麼強大的方法來完成。 – 2009-09-21 15:33:57
感謝您的更新。我其實從來沒有像Python中的Metaclasses一樣深入。也許這是一個很好的理由開始閱讀他們。 – pkit 2009-09-21 15:51:34