Hướng dẫn what is the need of property in python? - nhu cầu tài sản trong python là gì?

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

>>> human.__dict__
{'temperature': 37}

Do đó,

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.

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

# 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.60000000000001
7 và
37
98.60000000000001
8 mới.

Hơn nữa,

37
98.60000000000001
1 đã đượ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.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.


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

# 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.60000000000001
7 và
37
98.60000000000001
8 mới.

Hơn nữa,

37
98.60000000000001
1 đã đượ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())
0

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.

# 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

Do đó,

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())
2

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.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.60000000000001
1 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.600000000000017 và 37 98.600000000000018 mới.

Hơn nữa,

37
98.60000000000001
1 đã đượ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())
3

where,

  • 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ừ
    >>> 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 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())
4

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.

# 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ể 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())
6

Hai đ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.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í:

# 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())
8

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

Các tính chất của Python là gì?

Tài sản Python ()..
FGET (Tùy chọn) - Hàm để nhận giá trị thuộc tính. Mặc định là không ..
FSET (Tùy chọn) - Hàm để đặt giá trị thuộc tính. ....
FDEL (Tùy chọn) - Hàm để xóa giá trị thuộc tính. ....
Doc (Tùy chọn) - Một chuỗi chứa tài liệu (DocString) cho thuộc tính ..

Đối tượng thuộc tính trong Python là gì?

Thuộc tính là một đối tượng thuộc tính chứa một phương thức getter và một phương thức setter.an attribute object containing a getter and a setter method.

Làm thế nào chức năng tài sản hoạt động trong Python?

Hàm Python Property () trả về đối tượng của lớp thuộc tính và nó được sử dụng để tạo thuộc tính của một lớp.Tham số: fget () - Được sử dụng để nhận giá trị của thuộc tính.fset () - Được sử dụng để đặt giá trị của thuộc tính.returns the object of the property class and it is used to create property of a class. Parameters: fget() – used to get the value of attribute. fset() – used to set the value of attribute.

Tài sản và setter trong Python là gì?

Getters: Đây là các phương pháp được sử dụng trong lập trình hướng đối tượng (OOPS) giúp truy cập các thuộc tính riêng tư từ một lớp.Setters: Đây là các phương thức được sử dụng trong tính năng OOPS giúp đặt giá trị thành các thuộc tính riêng tư trong một lớp.