Việc sử dụng các phương thức getter và setter trong Python là gì?

Một lớp có thể có thêm một biến [đôi khi được gọi là thuộc tính]. Khi bạn tạo các đối tượng, mỗi đối tượng đó có các giá trị duy nhất cho các biến đó

Các biến lớp không cần phải được đặt trực tiếp. chúng có thể được đặt bằng các phương thức lớp. Đây là cách hướng đối tượng và giúp bạn tránh được những sai lầm

khóa học liên quan. Hoàn thành khóa học & bài tập lập trình Python

Thí dụ

Chúng tôi tạo một lớp với một thuộc tính. Từ lớp đó, chúng tôi tạo ra một số đối tượng

1
2
3
4
5
6
class Friend:    
def __init__[self]:
self.job = "None"

Alice = Friend[]
Bob = Friend[]

Các đối tượng này không có thuộc tính [công việc] được đặt. Để thiết lập, chúng ta có thể thiết lập trực tiếp nhưng đó là một cách làm không tốt. Thay vào đó chúng ta tạo ra hai phương thức. getJob[] và setJob[]

Cách "Pythonic" không phải là sử dụng "getters" và "setters", mà sử dụng các thuộc tính đơn giản, như câu hỏi minh họa 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ệ những người vô tội. nội trang]

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

[Mỗi cách sử dụng trình trang trí sao chép và cập nhật đối tượng thuộc tính trước đó, vì vậy lưu ý rằng bạn nên sử dụng cùng một tên cho mỗi hàm/phương thức đặt, nhận và xóa. ]

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]:  

Thứ nhất, cách trên không hiệu quả vì bạn không cung cấp đối số cho trường hợp 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], tức 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 trùng lặp 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 ta cũng có các hàm tích hợp sẵn

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à ________ 27

class Friend:    
def __init__[self]:
self.job = "None"

Alice = Friend[]
Bob = Friend[]
4

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
8 dùng để tạo getters và setters

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

class Friend:    
def __init__[self]:
self.job = "None"

Alice = Friend[]
Bob = Friend[]
6

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ì người dùng Python mong đợi. Theo quy tắc ít gây ngạc nhiên nhất, bạn nên cố gắng cung cấp cho người dùng của mình những gì họ mong đợi trừ khi bạn có lý do rất thuyết phục để làm ngược lại

trình diễn

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

class Friend:    
def __init__[self]:
self.job = "None"

Alice = Friend[]
Bob = Friend[]
8

[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. Điều này là để
obj = Obj[]
obj.attribute = value  
the_value = obj.attribute
del obj.attribute
0 sử dụng thuộc tính thông qua API công khai, đảm bảo thuộc tính được "bảo vệ". ]

Và cách 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
3

Những cái 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 bản sao của tài sản gốc. Điều này cho phép các lớp con sửa đổi hành vi đúng cách mà không làm thay đổi hành vi trong lớp cha

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

Bây giờ để nó hoạt động, bạn phải sử dụng các 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 điều này sẽ hữu ích ở đâu, nhưng trường hợp sử dụng là nếu bạn muốn thuộc tính chỉ nhận, đặt và/hoặc xóa. Có lẽ tốt nhất là dính vào cùng một thuộc tính ngữ nghĩa 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 chức năng đó bằng trình trang trí thuộc tính

Chủ Đề