Hướng dẫn should you use setters and getters in python? - bạn có nên sử dụng setters và getters trong python không?

Cách sử dụng getters và setters của Pythonic là gì?

Cách "Pythonic" không phải là sử dụng "getters" và "setters", mà là sử dụng các thuộc tính đơn giản, như câu hỏi thể hiện và

class Obj:
    """property demo"""
    #
    @property            # first decorate the getter method
    def attribute[self]: # This getter method name is *the* name
        return self._attribute
    #
    @attribute.setter    # the property decorates with `.setter` now
    def attribute[self, value]:   # name, e.g. "attribute", is the same
        self._attribute = value   # the "value" name isn't special
    #
    @attribute.deleter     # decorate with `.deleter`
    def attribute[self]:   # again, the method name is the same
        del self._attribute
1 để xóa [nhưng tên được thay đổi để bảo vệ ... tích hợp vô tội]:

value = 'something'

obj.attribute = value  
value = obj.attribute
del obj.attribute

Nếu sau này, bạn muốn sửa đổi cài đặt và nhận được, bạn có thể làm như vậy mà không cần phải thay đổi mã người dùng, bằng cách sử dụng trình trang trí

class Obj:
    """property demo"""
    #
    @property            # first decorate the getter method
    def attribute[self]: # This getter method name is *the* name
        return self._attribute
    #
    @attribute.setter    # the property decorates with `.setter` now
    def attribute[self, value]:   # name, e.g. "attribute", is the same
        self._attribute = value   # the "value" name isn't special
    #
    @attribute.deleter     # decorate with `.deleter`
    def attribute[self]:   # again, the method name is the same
        del self._attribute
2:

class Obj:
    """property demo"""
    #
    @property            # first decorate the getter method
    def attribute[self]: # This getter method name is *the* name
        return self._attribute
    #
    @attribute.setter    # the property decorates with `.setter` now
    def attribute[self, value]:   # name, e.g. "attribute", is the same
        self._attribute = value   # the "value" name isn't special
    #
    @attribute.deleter     # decorate with `.deleter`
    def attribute[self]:   # again, the method name is the same
        del self._attribute

.

Sau khi xác định ở trên, cài đặt ban đầu, nhận và xóa mã là như nhau:

obj = Obj[]
obj.attribute = value  
the_value = obj.attribute
del obj.attribute

Bạn nên tránh điều này:

def set_property[property,value]:  
def get_property[property]:  

Đầu tiên, những điều trên không hoạt động, vì bạn không cung cấp đối số cho trường hợp rằng thuộc tính sẽ được đặt thành [thường là

class Obj:
    """property demo"""
    #
    @property            # first decorate the getter method
    def attribute[self]: # This getter method name is *the* name
        return self._attribute
    #
    @attribute.setter    # the property decorates with `.setter` now
    def attribute[self, value]:   # name, e.g. "attribute", is the same
        self._attribute = value   # the "value" name isn't special
    #
    @attribute.deleter     # decorate with `.deleter`
    def attribute[self]:   # again, the method name is the same
        del self._attribute
3], đó sẽ là:

class Obj:

    def set_property[self, property, value]: # don't do this
        ...
    def get_property[self, property]:        # don't do this either
        ...

Thứ hai, điều này nhân đôi mục đích của hai phương pháp đặc biệt,

class Obj:
    """property demo"""
    #
    @property            # first decorate the getter method
    def attribute[self]: # This getter method name is *the* name
        return self._attribute
    #
    @attribute.setter    # the property decorates with `.setter` now
    def attribute[self, value]:   # name, e.g. "attribute", is the same
        self._attribute = value   # the "value" name isn't special
    #
    @attribute.deleter     # decorate with `.deleter`
    def attribute[self]:   # again, the method name is the same
        del self._attribute
4 và
class Obj:
    """property demo"""
    #
    @property            # first decorate the getter method
    def attribute[self]: # This getter method name is *the* name
        return self._attribute
    #
    @attribute.setter    # the property decorates with `.setter` now
    def attribute[self, value]:   # name, e.g. "attribute", is the same
        self._attribute = value   # the "value" name isn't special
    #
    @attribute.deleter     # decorate with `.deleter`
    def attribute[self]:   # again, the method name is the same
        del self._attribute
5.

Thứ ba, chúng tôi cũng có các chức năng tích hợp

class Obj:
    """property demo"""
    #
    @property            # first decorate the getter method
    def attribute[self]: # This getter method name is *the* name
        return self._attribute
    #
    @attribute.setter    # the property decorates with `.setter` now
    def attribute[self, value]:   # name, e.g. "attribute", is the same
        self._attribute = value   # the "value" name isn't special
    #
    @attribute.deleter     # decorate with `.deleter`
    def attribute[self]:   # again, the method name is the same
        del self._attribute
6 và
class Obj:
    """property demo"""
    #
    @property            # first decorate the getter method
    def attribute[self]: # This getter method name is *the* name
        return self._attribute
    #
    @attribute.setter    # the property decorates with `.setter` now
    def attribute[self, value]:   # name, e.g. "attribute", is the same
        self._attribute = value   # the "value" name isn't special
    #
    @attribute.deleter     # decorate with `.deleter`
    def attribute[self]:   # again, the method name is the same
        del self._attribute
7.

setattr[object, 'property_name', value]
getattr[object, 'property_name', default_value]  # default is optional

Bộ trang trí

class Obj:
    """property demo"""
    #
    @property            # first decorate the getter method
    def attribute[self]: # This getter method name is *the* name
        return self._attribute
    #
    @attribute.setter    # the property decorates with `.setter` now
    def attribute[self, value]:   # name, e.g. "attribute", is the same
        self._attribute = value   # the "value" name isn't special
    #
    @attribute.deleter     # decorate with `.deleter`
    def attribute[self]:   # again, the method name is the same
        del self._attribute
8 là để tạo ra getters và setters.

Ví dụ: chúng ta có thể sửa đổi hành vi cài đặt để đặt các hạn chế giá trị được đặt:

class Protective[object]:

    @property
    def protected_value[self]:
        return self._protected_value

    @protected_value.setter
    def protected_value[self, value]:
        if acceptable[value]: # e.g. type or range check
            self._protected_value = value

Nói chung, chúng tôi muốn tránh sử dụng

class Obj:
    """property demo"""
    #
    @property            # first decorate the getter method
    def attribute[self]: # This getter method name is *the* name
        return self._attribute
    #
    @attribute.setter    # the property decorates with `.setter` now
    def attribute[self, value]:   # name, e.g. "attribute", is the same
        self._attribute = value   # the "value" name isn't special
    #
    @attribute.deleter     # decorate with `.deleter`
    def attribute[self]:   # again, the method name is the same
        del self._attribute
2 và chỉ sử dụng các thuộc tính trực tiếp.

Đây là những gì được mong đợi bởi người dùng Python. Theo quy tắc ít nhất, bạn nên cố gắng cung cấp cho người dùng những gì họ mong đợi trừ khi bạn có một lý do rất thuyết phục ngược lại.

Trình diễn

Ví dụ, giả sử chúng tôi cần thuộc tính được bảo vệ của đối tượng của chúng tôi là một số nguyên từ 0 đến 100 và ngăn chặn việc xóa nó, với các thông báo phù hợp để thông báo cho người dùng về việc sử dụng đúng của nó:

class Protective[object]:
    """protected property demo"""
    #
    def __init__[self, start_protected_value=0]:
        self.protected_value = start_protected_value
    # 
    @property
    def protected_value[self]:
        return self._protected_value
    #
    @protected_value.setter
    def protected_value[self, value]:
        if value != int[value]:
            raise TypeError["protected_value must be an integer"]
        if 0 > p1 = Protective[3]
>>> p1.protected_value
3
>>> p1 = Protective[5.0]
>>> p1.protected_value
5
>>> p2 = Protective[-5]
Traceback [most recent call last]:
  File "", line 1, in 
  File "", line 3, in __init__
  File "", line 15, in protected_value
ValueError: protectected_value must be between 0 and 100 inclusive
>>> p1.protected_value = 7.3
Traceback [most recent call last]:
  File "", line 1, in 
  File "", line 17, in protected_value
TypeError: protected_value must be an integer
>>> p1.protected_value = 101
Traceback [most recent call last]:
  File "", line 1, in 
  File "", line 15, in protected_value
ValueError: protectected_value must be between 0 and 100 inclusive
>>> del p1.protected_value
Traceback [most recent call last]:
  File "", line 1, in 
  File "", line 18, in protected_value
AttributeError: do not delete, protected_value can be set to 0

Tên có quan trọng không?

Vâng, họ làm.

obj = Obj[]
obj.attribute = value  
the_value = obj.attribute
del obj.attribute
4 và
obj = Obj[]
obj.attribute = value  
the_value = obj.attribute
del obj.attribute
5 tạo các bản sao của thuộc tính gốc. Điều này cho phép các lớp con sửa đổi đúng hành vi mà không thay đổi hành vi trong cha mẹ.

class Obj:
    """property demo"""
    #
    @property
    def get_only[self]:
        return self._attribute
    #
    @get_only.setter
    def get_or_set[self, value]:
        self._attribute = value
    #
    @get_or_set.deleter
    def get_set_or_delete[self]:
        del self._attribute

Bây giờ để hoạt động này, bạn phải sử dụng tên tương ứng:

class Obj:
    """property demo"""
    #
    @property            # first decorate the getter method
    def attribute[self]: # This getter method name is *the* name
        return self._attribute
    #
    @attribute.setter    # the property decorates with `.setter` now
    def attribute[self, value]:   # name, e.g. "attribute", is the same
        self._attribute = value   # the "value" name isn't special
    #
    @attribute.deleter     # decorate with `.deleter`
    def attribute[self]:   # again, the method name is the same
        del self._attribute
0

Tôi không chắc nơi này sẽ hữu ích, nhưng trường hợp sử dụng là nếu bạn muốn có thuộc tính GET, SET và/hoặc XÓA CHỈ. Có lẽ tốt nhất để bám vào cùng một tài sản có cùng tên.

Sự kết luận

Bắt đầu với các thuộc tính đơn giản.

Nếu sau này bạn cần chức năng xung quanh cài đặt, nhận và xóa, bạn có thể thêm nó với bộ trang trí tài sản.

Tránh các chức năng có tên

obj = Obj[]
obj.attribute = value  
the_value = obj.attribute
del obj.attribute
6 và
obj = Obj[]
obj.attribute = value  
the_value = obj.attribute
del obj.attribute
7 - ​​đó là những gì thuộc tính dành cho.

Tôi có nên sử dụng getters và setters trong Python không?

Getters và setters trong Python thường được sử dụng khi: chúng tôi sử dụng getters & setters để thêm logic xác thực xung quanh việc nhận và đặt giá trị. Để tránh truy cập trực tiếp của trường lớp, tức là các biến riêng tư không thể được truy cập trực tiếp hoặc sửa đổi bởi người dùng bên ngoài.to add validation logic around getting and setting a value. To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by external user.

Bạn có nên luôn luôn sử dụng getters và setters?

Đóng gói là một trong những khái niệm cốt lõi của lập trình hướng đối tượng.Sử dụng getters và setters, theo tôi, theo tôi thực hành tốt.Một điều bạn nên tránh là có các thực thể bên ngoài gây rối với cấu trúc bên trong của lớp theo ý muốn.Ví dụ điển hình, xem xét có một tham số ngày.Using getters and setters, is always, in my opinion good practice. One thing you should avoid is to have external entities mess with the internal structure of your class at will. Typical example, consider having a dateOfBirth parameter.

Là getters và setters thực hành tốt?

Đó là thực hành lập trình tốt để không sử dụng getters và setters trong các lớp dự định nhiều hơn các gói dữ liệu [như một cấu trúc C].Họ phơi bày cấu trúc bên trong của lớp, vi phạm đóng gói và tăng đáng kể khớp nối. [like a C struct ]. They expose the internal structure of the class, violating encapsulation and greatly increasing coupling.

Tôi có thể sử dụng gì thay vì getters và setters?

Bạn có thể sử dụng Lombok - để tránh thủ công phương thức getter và setter.Nhưng nó tự tạo ra.Việc sử dụng Lombok làm giảm đáng kể số lượng mã.Tôi thấy nó khá tốt và dễ sử dụng.lombok - to manually avoid getter and setter method. But it create by itself. The using of lombok significantly reduces a lot number of code. I found it pretty fine and easy to use.

Bài Viết Liên Quan

Chủ Đề