Hướng dẫn should i use getters in python? - tôi có nên sử dụng 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 <= 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.

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

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.

Getters nên công khai hay riêng tư?

Nói chung, họ nên được công khai. Nếu chúng là riêng tư, chúng chỉ có thể được gọi từ trong lớp của bạn và, vì bạn đã có quyền truy cập vào các biến riêng trong lớp của bạn, sẽ dự phòng. Điểm của chúng là cho phép truy cập vào các biến này sang các đối tượng khác, bên ngoài.. If they are private they can only be called from within your class and, since you already have access to the private variables within your class, are redundant. The point of them is to allow access to these variables to other, outside, objects.

Getter được sử dụng gì trong Python?

Hàm getAttr () trả về giá trị của thuộc tính được chỉ định từ đối tượng được chỉ định.returns the value of the specified attribute from the specified object.

Tại sao getters và setters tốt hơn công khai?

Sự khác biệt chính giữa việc tạo ra một trường công khai so với phơi bày nó thông qua getters/setters đang nắm giữ quyền kiểm soát tài sản.Nếu bạn công khai trường, điều đó có nghĩa là bạn cung cấp quyền truy cập trực tiếp vào người gọi.Sau đó, người gọi có thể làm bất cứ điều gì với lĩnh vực của bạn, một cách cố ý hoặc vô tình.holding control over the property. If you make a field public, it means you provide direct access to the caller. Then, the caller can do anything with your field, either knowingly or unknowingly.