Five magic methods related to Python properties

This article has participated in the "Newcomer Creation Ceremony" activity, and started the road of Nuggets creation together

foreword

Today, I want to introduce five magic methods to you. They are all related to Python attributes, involving getting, deleting and modifying attributes. Let's take a look.

__getattribute__ method

Let's start by defining a simple class with no problem accessing properties.

class User:

    def __init__(self, name, sex):
        self.name = name
        self.sex = sex


u1 = User('li', 'male')
print(u1.name)

li
复制代码

Then we add the __getattribute__ method, and the access attribute will be handed over to this method.

class User:

    def __getattribute__(self, item):
        return 6

    def __init__(self, name, sex):
        self.name = name
        self.sex = sex


u1 = User('li', 'male')
print(u1.name)

6
复制代码

What's even more amazing is that it returns 6 whether or not this property exists.

class User:

    def __getattribute__(self, item):
        return 6

    def __init__(self, name, sex):
        self.name = name
        self.sex = sex


u1 = User('li', 'male')
print(u1.test)

6
复制代码
  • Triggered when: Triggered when the object member property is accessed, whether it exists or not.
  • Role: Do some processing on the attribute.
  • Parameters: self is the current object, item is a string to access the property name.
  • Return value: property value.

It should be noted here that the return value must not use self.name, which will recurse infinitely. We can use the __getattribute__ method of object to access.

class User:

    def __getattribute__(self, item):
        return object.__getattribute__(self, item)

    def __init__(self, name, sex):
        self.name = name
        self.sex = sex


u1 = User('li', 'male')
print(u1.name)

li
复制代码

__getattr__ method

  • Trigger Time: Triggered when a non-existent object property is accessed.
  • Effect: When accessing a non-existent property, no error will be reported.
  • Parameters: self is the current object, item is a string to access the property name.
  • Return value: property value.

Let's take a simple example, that is, the user may output the attribute name, then we all return the name attribute uniformly.

class User:

    def __getattr__(self, item):
        return self.name

    def __init__(self, name, sex):
        self.name = name
        self.sex = sex


u1 = User('li', 'male')
print(u1.na2me)

li
复制代码

__setattr__ method

  • Trigger Time: Triggered when adding and modifying object properties.
  • Role: Restrict the operation of adding and modifying object properties.
  • Parameters: self is the current object, key is the property name of the set object, and value is the set value.
  • Return value: None.

For example, we allow users to change the name, but not the sex.

class User:

    sex = 'male'

    def __setattr__(self, key, value):
        if key == 'sex':
            pass
        else:
            object.__setattr__(self, key, value)

    def __init__(self, name):
        self.name = name


u1 = User('li')
u1.name = 'test'
u1.sex = 'female'
print(u1.name, u1.sex)

test male
复制代码

__delattr__ method

  • Trigger Time: Triggered when an object property is deleted.
  • Role: Restrict the operation of adding and modifying object properties.
  • Parameters: self is the current object, item is the property name of the deleted object.
  • Return value: None.

We can let users delete sex, but not name.

class User:

    def __delattr__(self, item):
        if item == 'sex':
            pass
        else:
            object.__delattr__(self, item)

    def __init__(self, name, sex):
        self.name = name
        self.sex = sex


u1 = User('li', 'male')
del u1.sex
print(u1.sex)
del u1.name
print(u1.name)

male
AttributeError: 'User' object has no attribute 'name'
复制代码

__dir__ method

This method returns a list of all member names of a class or object, which is not used much.

property access order

Finally, I list the order of attribute access to you for your reference and study.

  • __getattribute__
  • data descriptor
  • properties of the current object
  • class properties
  • non-data descriptor
  • parent class properties
  • __getattr__

That's it for today's sharing, see you next time~

Guess you like

Origin juejin.im/post/7079362967250141192