How to define properties in __init__

前端 未结 3 1017

I whish to define properties in a class from a member function. Below is some test code showing how I would like this to work. However I don\'t get the expected behaviour.

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-05 20:39

    This does what you wanted:

    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 
    

    Another way to do it would be a metaclass ... but they confuse a lot of people ^^.

    Because I'm bored:

    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 
    

提交回复
热议问题