Hướng dẫn should i use getter and setter in python? - tôi có nên sử dụng getter và setter 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 <= value <= 100:
            self._protected_value = int(value)
        else:
            raise ValueError("protected_value must be " +
                             "between 0 and 100 inclusive")
    #
    @protected_value.deleter
    def protected_value(self):
        raise AttributeError("do not delete, protected_value can be set to 0")

(Lưu ý rằng

obj = Obj()
obj.attribute = value  
the_value = obj.attribute
del obj.attribute
0 đề cập đến
obj = Obj()
obj.attribute = value  
the_value = obj.attribute
del obj.attribute
1 nhưng các phương thức thuộc tính đề cập đến
obj = Obj()
obj.attribute = value  
the_value = obj.attribute
del obj.attribute
2.

Và cách sử dụng:

>>> 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.

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

Getters và setters được sử dụng để bảo vệ dữ liệu của bạn, đặc biệt là khi tạo các lớp. Đối với mỗi biến thể hiện, một phương thức Getter trả về giá trị của nó trong khi một phương thức setter đặt hoặc cập nhật giá trị của nó. Cho rằng, getters và setters còn được gọi là người truy cập và đột biến, tương ứng.. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.

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ã.lombok - to manually avoid getter and setter method. But it create by itself. The using of lombok significantly reduces a lot number of code.

Ưu điểm của việc sử dụng getters và setters là gì?

1. Phương thức Getter và Setter cung cấp cho bạn kiểm soát tập trung về cách một trường nhất định được khởi tạo và cung cấp cho máy khách, điều này giúp xác minh và gỡ lỗi dễ dàng hơn nhiều.Để xem chủ đề nào đang truy cập và giá trị nào sẽ được đưa ra, bạn có thể dễ dàng đặt các điểm dừng hoặc câu lệnh in.2.gives you centralized control of how a certain field is initialized and provided to the client, which makes it much easier to verify and debug. To see which thread is accessing and what values are going out, you can easily place breakpoints or a print statement. 2.

Khi nào tôi nên sử dụng @Property trong Python?

@Property là một công cụ trang trí tích hợp cho hàm tài sản () trong Python.Nó được sử dụng để cung cấp chức năng "đặc biệt" cho một số phương pháp nhất định để làm cho chúng hoạt động như getters, setters hoặc deleter khi chúng ta xác định các thuộc tính trong một lớp.to give "special" functionality to certain methods to make them act as getters, setters, or deleters when we define properties in a class.