Do you use the get/set pattern (in Python)?

后端 未结 8 1973
长情又很酷
长情又很酷 2020-12-12 13:25

Using get/set seems to be a common practice in Java (for various reasons), but I hardly see Python code that uses this.

Why do you use or avoid get/set methods in Py

8条回答
  •  天命终不由人
    2020-12-12 14:04

    In python, you can just access the attribute directly because it is public:

    class MyClass:
    
        def __init__(self):
            self.my_attribute = 0  
    
    my_object = MyClass()
    my_object.my_attribute = 1 # etc.
    

    If you want to do something on access or mutation of the attribute, you can use properties:

    class MyClass:
    
        def __init__(self):
            self._my_attribute = 0
    
        @property
        def my_attribute(self):
            # Do something if you want
            return self._my_attribute
    
        @my_attribute.setter
        def my_attribute(self, value):
            # Do something if you want
            self._my_attribute = value
    

    Crucially, the client code remains the same.

提交回复
热议问题