Lập trình Python cung cấp cho chúng tôi một bộ 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 sâu vào chi tiết về 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 là gì, trước tiên chúng ta hãy xây dựng trực giác về lý do tại sao nó sẽ cần thiết ngay từ đầu.Lớp không có getters và setters
Chúng ta hãy giả sử rằng chúng ta quyết định tạo ra 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 ra khỏi lớp này và thao tác thuộc tính
37 98.600000000000011 như chúng ta 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 bổ sung khi chuyển đổi thành Fahrenheit là do lỗi số học điểm nổi. Để tìm hiểu thêm, hãy truy cập lỗi số học của Python Point.
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.600000000000011 Như được hiển thị ở trên, Python tìm kiếm nó trong thuộc tính từ điển
37 98.600000000000013 tích hợp của đối tượng.
>>> human.__dict__
{'temperature': 37}
Do đó,
37 98.600000000000014 nội bộ trở thành
37 98.600000000000015.
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 C, được xác định ở trên. Chúng tôi biết rằng nhiệt độ của bất kỳ vật thể nào cũng không thể đạt dưới -273,15 độ 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 các hạn chế trên sẽ là ẩn thuộc tính
37 98.600000000000011 [làm cho nó riêng tư] và xác định các phương thức Getter và Setter mới để thao tác nó. Điều này có thể được thực hiện như sau:
# Making Getters and Setter methods
class Celsius:
def __init__[self, temperature=0]:
self.set_temperature[temperature]
def to_fahrenheit[self]:
return [self.get_temperature[] * 1.8] + 32
# getter method
def get_temperature[self]:
return self._temperature
# setter method
def set_temperature[self, value]:
if value < -273.15:
raise ValueError["Temperature below -273.15 is not possible."]
self._temperature = value
Như chúng ta có thể thấy, phương pháp trên giới thiệu hai phương thức
37 98.600000000000017 và
37 98.600000000000018 mới.
Hơn nữa,
37 98.600000000000011 đã được thay thế bằng
>>> human.__dict__
{'temperature': 37}
0. Một dấu gạch dưới >>> human.__dict__
{'temperature': 37}
1 lúc đầu được sử dụng để biểu thị các biến riêng trong Python.Bây giờ, hãy sử dụng triển khai này:
# Making Getters and Setter methods
class Celsius:
def __init__[self, temperature=0]:
self.set_temperature[temperature]
def to_fahrenheit[self]:
return [self.get_temperature[] * 1.8] + 32
# getter method
def get_temperature[self]:
return self._temperature
# setter method
def set_temperature[self, value]:
if value < -273.15:
raise ValueError["Temperature below -273.15 is not possible."]
self._temperature = value
# Create a new object, set_temperature[] internally called by __init__
human = Celsius[37]
# Get the temperature attribute via a getter
print[human.get_temperature[]]
# Get the to_fahrenheit method, get_temperature[] called by the method itself
print[human.to_fahrenheit[]]
# new constraint implementation
human.set_temperature[-300]
# Get the to_fahreheit method
print[human.to_fahrenheit[]]
Đầu ra
37 98.60000000000001 Traceback [most recent call last]: File "", line 30, in File "", line 16, in set_temperature ValueError: Temperature below -273.15 is not possible.
Các vị trí thập phân bổ sung khi chuyển đổi thành Fahrenheit là do lỗi số học điểm nổi. Để tìm hiểu thêm, hãy truy cập lỗi số học của Python Point.
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 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.: The private variables don't actually exist in
Python. There are simply norms to be followed. The language itself doesn't apply any restrictions.
>>> human._temperature = -300
>>> human.get_temperature[]
-300
Do đó,
37 98.600000000000014 nội bộ trở thành
37 98.600000000000015.
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 C, được xác định ở trên. Chúng tôi biết rằng nhiệt độ của bất kỳ vật thể nào cũng không thể đạt dưới -273,15 độ 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 các hạn chế trên sẽ là ẩn thuộc tính
37 98.600000000000011 [làm cho nó riêng tư] và xác định các phương thức Getter và Setter mới để thao tác nó. Điều này có thể được thực hiện như sau:
# using property class
class Celsius:
def __init__[self, temperature=0]:
self.temperature = temperature
def to_fahrenheit[self]:
return [self.temperature * 1.8] + 32
# getter
def get_temperature[self]:
print["Getting value..."]
return self._temperature
# setter
def set_temperature[self, value]:
print["Setting value..."]
if value < -273.15:
raise ValueError["Temperature below -273.15 is not possible"]
self._temperature = value
# creating a property object
temperature = property[get_temperature, set_temperature]
Như chúng ta có thể thấy, phương pháp trên giới thiệu hai phương thức
37 98.600000000000017 và
37 98.600000000000018 mới.
Hơn nữa,
37 98.600000000000011 đã được thay thế bằng
>>> human.__dict__
{'temperature': 37}
0. Một dấu gạch dưới >>> human.__dict__
{'temperature': 37}
1 lúc đầu được sử dụng để biểu thị các biến riêng trong Python.
Bây giờ, hãy sử dụng triển khai này:
# using property class
class Celsius:
def __init__[self, temperature=0]:
self.temperature = temperature
def to_fahrenheit[self]:
return [self.temperature * 1.8] + 32
# getter
def get_temperature[self]:
print["Getting value..."]
return self._temperature
# setter
def set_temperature[self, value]:
print["Setting value..."]
if value < -273.15:
raise ValueError["Temperature below -273.15 is not possible"]
self._temperature = value
# creating a property object
temperature = property[get_temperature, set_temperature]
human = Celsius[37]
print[human.temperature]
print[human.to_fahrenheit[]]
human.temperature = -300
Đầ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[]]
0Các vị trí thập phân bổ sung khi chuyển đổi thành Fahrenheit là do lỗi số học điểm nổi. Để tìm hiểu thêm, hãy truy cập lỗi số học của Python Point.
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.600000000000011 Như được hiển thị ở trên, Python tìm kiếm nó trong thuộc tính từ điển
37 98.600000000000013 tích hợp của đố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[]]
1Do đó, 37
98.60000000000001
4 nội bộ 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 C, được xác định ở trên. Chúng tôi biết rằng nhiệt độ của bất kỳ vật thể nào cũng không thể đạt dưới -273,15 độ 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[]]
2Hã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 các hạn chế trên sẽ là ẩn thuộc tính 37
98.60000000000001
1 [làm cho nó riêng tư] và xác định các phương thức Getter và Setter mới để thao tác nó. Điều này có thể được thực hiện như sau:: The actual temperature value is stored in
the private
>>> human.__dict__
{'temperature': 37}
0 variable. The 37 98.600000000000011 attribute is a property object which provides an interface to this private variable.
Như chúng ta có thể thấy, phương pháp trên giới thiệu hai phương thức 37
98.60000000000001
7 và 37
98.60000000000001
8 mới.
Hơn nữa,
37 98.600000000000011 đã được thay thế bằng
>>> human.__dict__
{'temperature': 37}
0. Một dấu gạch dưới >>> human.__dict__
{'temperature': 37}
1 lúc đầu được sử dụng để biểu thị các biến riêng 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[]]
3where,
- Bây giờ, hãy sử dụng triển khai này:
- Bản cập nhật này đã thực hiện thành công các hạn chế mới. Chúng tôi không còn được phép đặt nhiệt độ dưới -273,15 độ C.
- Lưu ý: Các biến riêng tư không thực sự tồn tại trong Python. Đơn giản là có các tiêu chuẩn để được tuân theo. Bản thân ngôn ngữ không áp dụng bất kỳ hạn chế nào.
- 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 tôi phải sửa đổi mã của họ từ
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.>>> human.__dict__ {'temperature': 37}
Việc tái cấu trúc này có thể gây ra vấn đề trong khi xử lý hàng trăm ngàn dòng 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[]]
4Nó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.# 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[]]
5có thể bị phá vỡ 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[]]
6Hai đoạn mã này là tương đương.
Các lập trình viên quen thuộc với các nhà trang trí Python có thể nhận ra rằng cấu trúc trên có thể được thực hiện như là nhà trang trí.
Chúng tôi thậm chí không thể xác định tên
# Making Getters and Setter methods
class Celsius:
def __init__[self, temperature=0]:
self.set_temperature[temperature]
def to_fahrenheit[self]:
return [self.get_temperature[] * 1.8] + 32
# getter method
def get_temperature[self]:
return self._temperature
# setter method
def set_temperature[self, value]:
if value < -273.15:
raise ValueError["Temperature below -273.15 is not possible."]
self._temperature = value
2 và # Making Getters and Setter methods
class Celsius:
def __init__[self, temperature=0]:
self.set_temperature[temperature]
def to_fahrenheit[self]:
return [self.get_temperature[] * 1.8] + 32
# getter method
def get_temperature[self]:
return self._temperature
# setter method
def set_temperature[self, value]:
if value < -273.15:
raise ValueError["Temperature below -273.15 is not possible."]
self._temperature = value
3 vì chúng không cần thiết và gây ô 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.600000000000011 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í:
# 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[]]
7Đầ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[]]
8Việc thực hiện trên là đơn giản và hiệu quả. Đó là cách khuyến nghị để sử dụng
>>> human.__dict__
{'temperature': 37}
7.