Getters và setters hoạt động như thế nào trong python?

Lập trình Python cung cấp cho chúng ta một trình trang trí

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
9 tích hợp giúp việc sử dụng getter và setters dễ dàng hơn nhiều trong Lập trình hướng đối tượng

Trước khi đi vào chi tiết về

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
9 decorator là gì, trước tiên chúng ta hãy xây dựng một trực giác về lý do tại sao nó lại cần thiết ngay từ đầu


Lớp không có Getters và Setters

Giả sử rằng chúng ta quyết định tạo một lớp lưu trữ nhiệt độ theo độ C. Nó cũng sẽ thực hiện một phương pháp để chuyển đổi nhiệt độ thành độ Fahrenheit. Một cách để làm điều này là như sau

class Celsius:
    def __init__(self, temperature = 0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32

Chúng ta có thể tạo các đối tượng từ lớp này và thao tác với thuộc tính

37
98.60000000000001
1 theo ý muốn

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())

đầu ra

37
98.60000000000001

Các vị trí thập phân thừa khi chuyển đổi thành Fahrenheit là do lỗi số học dấu phẩy động. Để tìm hiểu thêm, hãy truy cập Lỗi số học dấu phẩy động Python

Bất cứ khi nào chúng tôi gán hoặc truy xuất bất kỳ thuộc tính đối tượng nào như

37
98.60000000000001
1 như được hiển thị ở trên, Python sẽ tìm kiếm nó trong thuộc tính từ điển
37
98.60000000000001
3 tích hợp của đối tượng

________số 8

Do đó,

37
98.60000000000001
4 bên trong trở thành
37
98.60000000000001
5


Sử dụng Getters và Setters

Giả sử chúng ta muốn mở rộng khả năng sử dụng của lớp Celsius được định nghĩa ở trên. Chúng ta biết rằng nhiệt độ của bất kỳ vật thể nào không thể xuống dưới -273. 15 độ C (Không độ tuyệt đối trong Nhiệt động lực học)

Hãy cập nhật mã của chúng tôi để thực hiện ràng buộc giá trị này

Một giải pháp rõ ràng cho hạn chế trên là ẩn thuộc tính

37
98.60000000000001
1 (đặt nó ở chế độ riêng tư) và xác định các phương thức getter và setter mới để thao tác với nó. Điều này có thể được thực hiện như sau

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
2

Như chúng ta có thể thấy, phương thức trên giới thiệu hai phương thức mới

37
98.60000000000001
7 và
37
98.60000000000001
8

Hơn nữa,

37
98.60000000000001
1 đã được thay thế bằng
>>> human.__dict__
{'temperature': 37}
0. Dấu gạch dưới
>>> human.__dict__
{'temperature': 37}
1 ở đầu được sử dụng để biểu thị các biến riêng tư trong Python


Bây giờ, hãy sử dụng triển khai này

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
8

đầu ra

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
9

Bản cập nhật này đã triển khai thành công hạn chế mới. Chúng tôi không còn được phép đặt nhiệt độ dưới -273. 15 độ C

Ghi chú. Các biến riêng tư không thực sự tồn tại trong Python. Đơn giản là có những chuẩn mực phải tuân theo. Bản thân ngôn ngữ không áp dụng bất kỳ hạn chế nào

class Celsius:
    def __init__(self, temperature = 0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32
0

Tuy nhiên, vấn đề lớn hơn với bản cập nhật trên là tất cả các chương trình đã triển khai lớp trước của chúng ta phải sửa đổi mã của chúng từ

>>> human.__dict__
{'temperature': 37}
2 thành
>>> human.__dict__
{'temperature': 37}
3 và tất cả các biểu thức như
>>> human.__dict__
{'temperature': 37}
4 thành
>>> human.__dict__
{'temperature': 37}
5

Việc tái cấu trúc này có thể gây ra sự cố khi xử lý hàng trăm nghìn dòng mã

Nói chung, bản cập nhật mới của chúng tôi không tương thích ngược. Đây là nơi

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
9 đến để giải cứu


Lớp tài sản

Một cách Pythonic để giải quyết vấn đề trên là sử dụng lớp

>>> human.__dict__
{'temperature': 37}
7. Đây là cách chúng tôi có thể cập nhật mã của mình

class Celsius:
    def __init__(self, temperature = 0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32
7

Chúng tôi đã thêm một hàm

>>> human.__dict__
{'temperature': 37}
8 bên trong
37
98.60000000000001
7 và
37
98.60000000000001
8 để quan sát rõ ràng rằng chúng đang được thực thi

Dòng cuối cùng của mã tạo đối tượng thuộc tính

37
98.60000000000001
1. Nói một cách đơn giản, thuộc tính gắn một số mã (
# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
22 và
# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
23) vào thuộc tính thành viên truy cập (
37
98.60000000000001
1)

Hãy sử dụng mã cập nhật này

37
98.60000000000001
5

đầu ra

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
0

Như chúng ta có thể thấy, bất kỳ mã nào truy xuất giá trị của

37
98.60000000000001
1 sẽ tự động gọi
37
98.60000000000001
7 thay vì tra cứu từ điển (__dict__). Tương tự, bất kỳ mã nào gán giá trị cho
37
98.60000000000001
1 sẽ tự động gọi
37
98.60000000000001
8

Chúng ta thậm chí có thể thấy ở trên rằng

37
98.60000000000001
8 đã được gọi ngay cả khi chúng ta tạo một đối tượng

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
1

Bạn có đoán được tại sao không?

Lý do là khi một đối tượng được tạo, phương thức

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
80 được gọi. Phương thức này có dòng
# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
81. Biểu thức này tự động gọi
37
98.60000000000001
8

Tương tự, mọi truy cập như

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
83 sẽ tự động gọi
37
98.60000000000001
7. Đây là những gì tài sản làm. Dưới đây là một vài ví dụ khác

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
2

Bằng cách sử dụng

>>> human.__dict__
{'temperature': 37}
7, chúng ta có thể thấy rằng không cần sửa đổi gì khi triển khai ràng buộc giá trị. Do đó, việc triển khai của chúng tôi tương thích ngược

Ghi chú. Giá trị nhiệt độ thực tế được lưu trữ trong biến

>>> human.__dict__
{'temperature': 37}
0 riêng. Thuộc tính
37
98.60000000000001
1 là một đối tượng thuộc tính cung cấp giao diện cho biến riêng tư này


Người trang trí @property

Trong Python,

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
88 là một hàm tích hợp để tạo và trả về một đối tượng
>>> human.__dict__
{'temperature': 37}
7. Cú pháp của hàm này là

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
3

ở đâu,

  • # Basic method of setting and getting attributes in Python
    class Celsius:
        def __init__(self, temperature=0):
            self.temperature = temperature
    
        def to_fahrenheit(self):
            return (self.temperature * 1.8) + 32
    
    
    # Create a new object
    human = Celsius()
    
    # Set the temperature
    human.temperature = 37
    
    # Get the temperature attribute
    print(human.temperature)
    
    # Get the to_fahrenheit method
    print(human.to_fahrenheit())
    90 là hàm lấy giá trị của thuộc tính
  • # Basic method of setting and getting attributes in Python
    class Celsius:
        def __init__(self, temperature=0):
            self.temperature = temperature
    
        def to_fahrenheit(self):
            return (self.temperature * 1.8) + 32
    
    
    # Create a new object
    human = Celsius()
    
    # Set the temperature
    human.temperature = 37
    
    # Get the temperature attribute
    print(human.temperature)
    
    # Get the to_fahrenheit method
    print(human.to_fahrenheit())
    91 là hàm đặt giá trị của thuộc tính
  • # Basic method of setting and getting attributes in Python
    class Celsius:
        def __init__(self, temperature=0):
            self.temperature = temperature
    
        def to_fahrenheit(self):
            return (self.temperature * 1.8) + 32
    
    
    # Create a new object
    human = Celsius()
    
    # Set the temperature
    human.temperature = 37
    
    # Get the temperature attribute
    print(human.temperature)
    
    # Get the to_fahrenheit method
    print(human.to_fahrenheit())
    92 là chức năng xóa thuộc tính
  • # Basic method of setting and getting attributes in Python
    class Celsius:
        def __init__(self, temperature=0):
            self.temperature = temperature
    
        def to_fahrenheit(self):
            return (self.temperature * 1.8) + 32
    
    
    # Create a new object
    human = Celsius()
    
    # Set the temperature
    human.temperature = 37
    
    # Get the temperature attribute
    print(human.temperature)
    
    # Get the to_fahrenheit method
    print(human.to_fahrenheit())
    93 là một chuỗi (giống như một bình luận)

Như đã thấy từ quá trình triển khai, các đối số chức năng này là tùy chọn. Vì vậy, một đối tượng thuộc tính có thể được tạo đơn giản như sau

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
4

Một đối tượng thuộc tính có ba phương thức,

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
94,
# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
95 và
# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
96 để chỉ định
# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
90,
# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
91 và
# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
92 sau đó. Điều này có nghĩa là, dòng

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
5

có thể được chia nhỏ như

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
6

Hai đoạn mã này tương đương nhau

Các lập trình viên quen thuộc với Trình trang trí Python có thể nhận ra rằng cấu trúc trên có thể được triển khai dưới dạng trình trang trí

Chúng tôi thậm chí không thể định nghĩa tên

# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
22 và
# Basic method of setting and getting attributes in Python
class Celsius:
    def __init__(self, temperature=0):
        self.temperature = temperature

    def to_fahrenheit(self):
        return (self.temperature * 1.8) + 32


# Create a new object
human = Celsius()

# Set the temperature
human.temperature = 37

# Get the temperature attribute
print(human.temperature)

# Get the to_fahrenheit method
print(human.to_fahrenheit())
23 vì chúng không cần thiết và làm ô nhiễm không gian tên lớp

Đối với điều này, chúng tôi sử dụng lại tên

37
98.60000000000001
1 trong khi xác định các hàm getter và setter của chúng tôi. Hãy xem cách thực hiện điều này như một người trang trí

Làm thế nào để một getter và setter hoạt động?

Getter trả về giá trị (accessors), nó trả về giá trị của kiểu dữ liệu int, String, double, float, v.v. Để thuận tiện cho chương trình, getter bắt đầu bằng từ “get” theo sau là tên biến. Trong khi Setter đặt hoặc cập nhật giá trị (bộ biến đổi). Nó đặt giá trị cho bất kỳ biến nào được sử dụng trong các chương trình của lớp

Làm thế nào để getter và setter giúp thực hiện đóng gói trong Python?

Mục đích chính của việc sử dụng getters và setters trong các chương trình hướng đối tượng là để đảm bảo đóng gói dữ liệu. Sử dụng phương thức getter để truy cập các thành viên dữ liệu và các phương thức setter để sửa đổi các thành viên dữ liệu . Trong Python, các biến riêng tư không phải là các trường ẩn như trong các ngôn ngữ lập trình khác.

Làm thế nào chúng ta có thể sử dụng phương thức Get() và set() và nêu rõ mục đích của nó?

Phương thức get trả về giá trị của tên biến. Phương thức set nhận một tham số ( newName ) và gán nó cho biến name . Từ khóa this được sử dụng để chỉ đối tượng hiện tại.