Hướng dẫn dùng python __getattr__ python

Description¶

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self).

Syntax¶

object. __getattr__(self, name)

selfRequired. Instance of the class, passed automatically on call.nameRequired. The name of the attribute.

Example¶

>>> class Frob:
...     def __init__(self, bamf):
...         self.bamf = bamf
...     def __getattr__(self, name):
...         return 'Frob does not have `{}` attribute.'.format(str(name))
...
>>> f = Frob("bamf")
>>> f.bar
'Frob does not have `bar` attribute.'
>>> f.bamf
'bamf'

Hãy xem một số ví dụ đơn giản về cả hai __getattr____getattribute__phương pháp ma thuật.

__getattr__

Python sẽ gọi __getattr__phương thức bất cứ khi nào bạn yêu cầu một thuộc tính chưa được xác định. Trong ví dụ sau lớp học của tôi Đếm không có __getattr__phương pháp. Bây giờ trong chính khi tôi cố gắng truy cập cả hai obj1.myminobj1.mymaxthuộc tính mọi thứ hoạt động tốt. Nhưng khi tôi cố gắng truy cập obj1.mycurrentthuộc tính - Python cho tôiAttributeError: 'Count' object has no attribute 'mycurrent'

class Count():
    def __init__(self,mymin,mymax):
        self.mymin=mymin
        self.mymax=mymax

obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.mycurrent)  --> AttributeError: 'Count' object has no attribute 'mycurrent'

Bây giờ lớp học của tôi Đếm__getattr__phương pháp. Bây giờ khi tôi cố gắng truy cập obj1.mycurrentthuộc tính - python trả về cho tôi bất cứ điều gì tôi đã thực hiện trong __getattr__phương thức của mình . Trong ví dụ của tôi bất cứ khi nào tôi cố gắng gọi một thuộc tính không tồn tại, python tạo thuộc tính đó và đặt nó thành giá trị nguyên 0.

class Count:
    def __init__(self,mymin,mymax):
        self.mymin=mymin
        self.mymax=mymax    

    def __getattr__(self, item):
        self.__dict__[item]=0
        return 0

obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.mycurrent1)

__getattribute__

Bây giờ hãy xem __getattribute__phương thức. Nếu bạn có __getattribute__phương thức trong lớp, python gọi phương thức này cho mọi thuộc tính bất kể nó có tồn tại hay không. Vậy tại sao chúng ta cần __getattribute__phương pháp? Một lý do chính là bạn có thể ngăn truy cập vào các thuộc tính và làm cho chúng an toàn hơn như trong ví dụ sau.

Bất cứ khi nào ai đó cố gắng truy cập các thuộc tính của tôi bắt đầu bằng chuỗi con trăn 'cur', chuỗi AttributeErrorngoại lệ sẽ tăng ngoại lệ. Nếu không, nó trả về thuộc tính đó.

class Count:

    def __init__(self,mymin,mymax):
        self.mymin=mymin
        self.mymax=mymax
        self.current=None

    def __getattribute__(self, item):
        if item.startswith('cur'):
            raise AttributeError
        return object.__getattribute__(self,item) 
        # or you can use ---return super().__getattribute__(item)

obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.current)

Quan trọng: Để tránh đệ quy vô hạn trong __getattribute__phương thức, việc triển khai nó phải luôn gọi phương thức lớp cơ sở có cùng tên để truy cập bất kỳ thuộc tính nào mà nó cần. Ví dụ: object.__getattribute__(self, name)hoặc super().__getattribute__(item)khôngself.__dict__[item]

QUAN TRỌNG

Nếu lớp của bạn chứa cả phương thức ma thuật getattrgetattribution thì __getattribute__được gọi đầu tiên. Nhưng nếu __getattribute__tăng AttributeErrorngoại lệ thì ngoại lệ sẽ bị bỏ qua và __getattr__phương thức sẽ được gọi. Xem ví dụ sau:

class Count(object):

    def __init__(self,mymin,mymax):
        self.mymin=mymin
        self.mymax=mymax
        self.current=None

    def __getattr__(self, item):
            self.__dict__[item]=0
            return 0

    def __getattribute__(self, item):
        if item.startswith('cur'):
            raise AttributeError
        return object.__getattribute__(self,item)
        # or you can use ---return super().__getattribute__(item)
        # note this class subclass object

obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.current)

93 hữu ích 1 bình luận chia sẻ