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

后端 未结 8 2305
盖世英雄少女心
盖世英雄少女心 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条回答
  •  无人共我
    2020-11-22 00:06

    Try this: Python Property

    The sample code is:

    class C(object):
        def __init__(self):
            self._x = None
    
        @property
        def x(self):
            """I'm the 'x' property."""
            print("getter of x called")
            return self._x
    
        @x.setter
        def x(self, value):
            print("setter of x called")
            self._x = value
    
        @x.deleter
        def x(self):
            print("deleter of x called")
            del self._x
    
    
    c = C()
    c.x = 'foo'  # setter called
    foo = c.x    # getter called
    del c.x      # deleter called
    

提交回复
热议问题