What's the pythonic way to use getters and setters?

后端 未结 8 2426
盖世英雄少女心
盖世英雄少女心 2020-11-21 23:05

I\'m doing it like:

def set_property(property,value):  
def get_property(property):  

or

object.property = value  
value =         


        
8条回答
  •  猫巷女王i
    2020-11-21 23:52

    This is an old question but the topic is very important and always current. In case anyone wants to go beyond simple getters/setters i have wrote an article about superpowered properties in python with support for slots, observability and reduced boilerplate code.

    from objects import properties, self_properties
    
    
    class Car:
        with properties(locals(), 'meta') as meta:
    
            @meta.prop(read_only=True)
            def brand(self) -> str:
                """Brand"""
    
            @meta.prop(read_only=True)
            def max_speed(self) -> float:
                """Maximum car speed"""
    
            @meta.prop(listener='_on_acceleration')
            def speed(self) -> float:
                """Speed of the car"""
                return 0  # Default stopped
    
            @meta.prop(listener='_on_off_listener')
            def on(self) -> bool:
                """Engine state"""
                return False
    
        def __init__(self, brand: str, max_speed: float = 200):
            self_properties(self, locals())
    
        def _on_off_listener(self, prop, old, on):
            if on:
                print(f"{self.brand} Turned on, Runnnnnn")
            else:
                self._speed = 0
                print(f"{self.brand} Turned off.")
    
        def _on_acceleration(self, prop, old, speed):
            if self.on:
                if speed > self.max_speed:
                    print(f"{self.brand} {speed}km/h Bang! Engine exploded!")
                    self.on = False
                else:
                    print(f"{self.brand} New speed: {speed}km/h")
            else:
                print(f"{self.brand} Car is off, no speed change")
    

    This class can be used like this:

    mycar = Car('Ford')
    
    # Car is turned off
    for speed in range(0, 300, 50):
        mycar.speed = speed
    
    # Car is turned on
    mycar.on = True
    for speed in range(0, 350, 50):
        mycar.speed = speed
    

    This code will produce the following output:

    Ford Car is off, no speed change
    Ford Car is off, no speed change
    Ford Car is off, no speed change
    Ford Car is off, no speed change
    Ford Car is off, no speed change
    Ford Car is off, no speed change
    Ford Turned on, Runnnnnn
    Ford New speed: 0km/h
    Ford New speed: 50km/h
    Ford New speed: 100km/h
    Ford New speed: 150km/h
    Ford New speed: 200km/h
    Ford 250km/h Bang! Engine exploded!
    Ford Turned off.
    Ford Car is off, no speed change
    

    More info about how and why here: https://mnesarco.github.io/blog/2020/07/23/python-metaprogramming-properties-on-steroids

提交回复
热议问题