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

后端 未结 8 2308
盖世英雄少女心
盖世英雄少女心 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-21 23:52

    You can use the magic methods __getattribute__ and __setattr__.

    class MyClass:
        def __init__(self, attrvalue):
            self.myattr = attrvalue
        def __getattribute__(self, attr):
            if attr == "myattr":
                #Getter for myattr
        def __setattr__(self, attr):
            if attr == "myattr":
                #Setter for myattr
    

    Be aware that __getattr__ and __getattribute__ are not the same. __getattr__ is only invoked when the attribute is not found.

提交回复
热议问题