Hướng dẫn python override getter - python ghi đè getter

Vì vậy, tôi đang cố gắng tìm ra cách tốt nhất [thanh lịch nhất với số lượng mã ít nhất] để cho phép ghi đè các chức năng cụ thể của một thuộc tính [ví dụ: chỉ là getter, chỉ là setter, v.v.] trong Python. Tôi là một fan hâm mộ của cách thực hiện các thuộc tính sau đây, do thực tế là tất cả các phương thức của chúng được gói gọn trong cùng một khối mã được thụt vào bắt đầu tiếp theo]:

@apply
def foo[]:
    """A foobar"""
    def fget[self]:
        return self._foo
    def fset[self, val]:
        self._foo = val
    return property[**locals[]]

Tuy nhiên, nếu tôi muốn kế thừa từ một lớp xác định các thuộc tính theo cách này, và sau đó, nói, ghi đè chức năng setter foo, nó có vẻ khó khăn. Tôi đã thực hiện một số tìm kiếm và hầu hết các câu trả lời tôi đã tìm thấy là xác định các chức năng riêng biệt trong lớp cơ sở [ví dụ: getFoosetFoo], tạo rõ ràng định nghĩa thuộc tính từ chúng [ví dụ: foo = property[lambda x: x.getFoo[], lambda x, y: x.setFoo[y], lambda x: x.delFoo[]]], sau đó ghi đè getFoo, setFoodelFoo khi cần thiết.

Tôi không thích giải pháp này vì điều đó có nghĩa là tôi phải xác định Lambas cho mỗi thuộc tính, và sau đó viết ra từng cuộc gọi chức năng [khi trước khi tôi có thể thực hiện

class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
0]. Tôi cũng không nhận được sự đóng gói mà ban đầu tôi đã có.

Lý tưởng nhất, những gì tôi muốn có thể làm sẽ là một cái gì đó như thế này:

class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something

Và sau đó, đầu ra sẽ trông giống như:

>>> a = A[]
>>> a.foo
8
>>> b = ATimesTwo[]
>>> b.foo
16

Về cơ bản,

class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
1 kế thừa hàm getter từ
class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
2 nhưng ghi đè chức năng setter. Có ai biết cách làm điều này [theo cách trông giống với ví dụ trên] không?
class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
3 sẽ trông như thế nào, và chức năng foo nên trở lại như thế nào?

Tham gia với chúng tôi và có quyền truy cập vào hàng ngàn hướng dẫn và một cộng đồng chuyên gia Pythonistas.

Mở khóa bài học này

Bài học này chỉ dành cho các thành viên. Tham gia với chúng tôi và có quyền truy cập vào hàng ngàn hướng dẫn và một cộng đồng chuyên gia Pythonistas.Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Mở khóa bài học này

Bài học này chỉ dành cho các thành viên. Tham gia với chúng tôi và có quyền truy cập vào hàng ngàn hướng dẫn và một cộng đồng chuyên gia Pythonistas. Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

  • Xin lỗi! Có vẻ như có một vấn đề với phát lại video 🙁 Điều này có thể là do sự cố ngừng hoạt động tạm thời hoặc do sự cố cấu hình với trình duyệt của bạn. Vui lòng xem Hướng dẫn khắc phục sự cố trình phát video của chúng tôi để giải quyết vấn đề.
  • Bảng điểm

Nhận xét & Thảo luận Overriding Properties in Subclasses. When you create Python classes that include properties and release them in a package or library, you should expect that your users do a wide variety of things with them.

00:00 Thuộc tính ghi đè trong các lớp con. Khi bạn tạo các lớp Python bao gồm các thuộc tính và phát hành chúng trong gói hoặc thư viện, bạn nên mong đợi rằng người dùng của bạn làm rất nhiều thứ với chúng. One of these things could be subclassing them to customize their functionalities. In these cases, your users have to be careful and be aware of a subtle gotcha.

00:14 Một trong những điều này có thể là phân lớp chúng để tùy chỉnh các chức năng của chúng. Trong những trường hợp này, người dùng của bạn phải cẩn thận và nhận thức được một gotcha tinh tế. If you partially override a property, then you lose the non-overridden functionality. For example, suppose you are coding an

class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
5 class to manage employee information in your company’s internal accounting system. You already have a class called
class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
6, and you think about subclassing it to reuse its functionality.

00:25 Nếu bạn ghi đè một phần một thuộc tính, thì bạn sẽ mất chức năng không phản hồi. Ví dụ: giả sử bạn đang mã hóa một lớp

class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
5 để quản lý thông tin nhân viên trong hệ thống kế toán nội bộ của công ty bạn. Bạn đã có một lớp gọi là
class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
6 và bạn nghĩ về việc phân lớp nó để sử dụng lại chức năng của nó.
class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
6 has a
class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
8 attribute implemented as a property. The current implementation of
class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
8 doesn’t meet the requirement of returning the name in uppercase letters.

01:01

class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
6 có thuộc tính
class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
8 được triển khai như một thuộc tính. Việc triển khai hiện tại của
class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
8 không đáp ứng yêu cầu trả về tên trong các chữ cái viết hoa.
Here’s how you end up solving this. In
class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
5, you override
class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
8 to make sure that when you access the attribute, you get the employee name in uppercase.

01:14 Ở đây, cách bạn kết thúc việc giải quyết điều này. Trong

class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
5, bạn ghi đè
class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
8 để đảm bảo rằng khi bạn truy cập thuộc tính, bạn sẽ nhận được tên nhân viên trong chữ hoa.
class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
5 works as you need. It returns the name using uppercase letters. However, subsequent tests uncover an unexpected behavior. You may be wondering what’s happened. When you override an existing property from a parent class, you override the whole functionality of that property.

02:03

class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
5 hoạt động như bạn cần. Nó trả về tên bằng chữ hoa. Tuy nhiên, các thử nghiệm tiếp theo phát hiện ra một hành vi bất ngờ. Bạn có thể tự hỏi những gì đã xảy ra. Khi bạn ghi đè một thuộc tính hiện có từ lớp cha, bạn sẽ ghi đè toàn bộ chức năng của thuộc tính đó. In this example, you reimplemented the getter method only. Because of that,
class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
8 lost the rest of the functionality from the base class. You don’t have a setter method any longer.

02:25 Trong ví dụ này, bạn chỉ tái tạo phương thức Getter. Do đó,

class A[object]:
    def __init__[self]:
        self.foo = 8
    @apply
    def foo[]:
        """A foobar"""
        def fget[self]:
            return self._foo
        def fset[self, val]:
            self._foo = val
        return property[**locals[]]

class ATimesTwo[A]:
    @some_decorator
    def foo[]:
        def fset[self, val]:
            self._foo = val * 2
        return something
8 đã mất phần còn lại của chức năng từ lớp cơ sở. Bạn không có một phương pháp setter nữa. The idea is that if you ever need to override a property in a subclass, then you should provide all of the functionality you need in the new version of the property at hand.

02:39 Ý tưởng là nếu bạn cần ghi đè một thuộc tính trong một lớp con, thì bạn nên cung cấp tất cả các chức năng bạn cần trong phiên bản mới của tài sản trong tay. With this code in place, you can now set the employee’s name without issue.

02:56 Với mã này, bây giờ bạn có thể đặt tên nhân viên mà không gặp vấn đề gì. Now that you’ve completed the content of the course, in the next section, you’ll review what you’ve learned.

03:29 Bây giờ bạn đã hoàn thành nội dung của khóa học, trong phần tiếp theo, bạn sẽ xem xét những gì bạn đã học được.

Làm thế nào để bạn ghi đè một đối tượng trong Python?defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.

Trong phương thức Python ghi đè xảy ra bằng cách xác định trong phương thức Lớp con A có cùng tên của một phương thức trong lớp cha. Khi bạn xác định một phương thức trong đối tượng, bạn thực hiện sau này có thể thỏa mãn cuộc gọi phương thức đó, vì vậy việc triển khai tổ tiên của nó không xuất hiện.

Bạn có thể ghi đè trong Python không?. This is an important feature of inheritance in Python. In method overriding, the child class can change its functions that are defined by its ancestral classes.

Bạn có thể ghi đè __ init __ không?

Trả lời #5: Có, bạn phải gọi __init__ cho mỗi lớp cha mẹ.Điều tương tự cũng xảy ra với các chức năng, nếu bạn đang ghi đè một chức năng tồn tại ở cả hai cha mẹ.Yes, you must call __init__ for each parent class. The same goes for functions, if you are overriding a function that exists in both parents.

Tài sản [] làm gì trong Python?

Thuộc tính của Python [] là cách pythonic để tránh các phương thức getter và setter chính thức trong mã của bạn.Hàm này cho phép bạn biến các thuộc tính lớp thành thuộc tính hoặc thuộc tính được quản lý.Vì thuộc tính [] là một hàm tích hợp, bạn có thể sử dụng nó mà không cần nhập bất cứ thứ gì.allows you to turn class attributes into properties or managed attributes. Since property[] is a built-in function, you can use it without importing anything.

Bài Viết Liên Quan

Chủ Đề