This article has participated in the activity of “New person creation Ceremony”, and started the road of digging gold creation together

preface

Today I’m going to show you five magic methods, all related to Python properties, that involve getting, deleting, and modifying properties. Let’s take a look.

The.__getattribute__ method

Let’s start by defining a simple class that has 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
Copy the code

After we add the __getAttribute__ method, the access attribute is handed to that 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
Copy the code

Even more amazing, this property will return 6 whether it exists or not.

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
Copy the code
  • Trigger time: Triggered when an object member property is accessed, whether it exists or not.
  • Action: Performs some processing on attributes.
  • Arguments: self is the current object, and item is the string that accesses the attribute name.
  • Return value: property value.

The important thing to note here is that the return value should never be self.name, as this will recurse indefinitely, and can be accessed using object’s __getAttribute__ method.

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
Copy the code

__getattr__ method

  • Trigger time: Triggered when an object property that does not exist is accessed.
  • Function: No error is reported when accessing nonexistent properties.
  • Arguments: self is the current object, and item is the string that accesses the attribute name.
  • Return value: property value.

Let’s take a simple example, where the user might output a property name, and we’ll all return the name property.

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
Copy the code

__setattr__ method

  • Trigger time: Trigger when object properties are added or modified.
  • Effect: Restricts the operation of adding and modifying object properties.
  • Parameters: self is the current object, key is the name of the set object property, and value is the set value.
  • Returned value: None.

For example, we let users change their name, not 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
Copy the code

__delattr__ method

  • Trigger time: Triggered when an object property is deleted.
  • Effect: Restricts the operation of adding and modifying object properties.
  • Arguments: self is the current object and item is the name of the property of the deleted object.
  • Returned value: None.

We can ask the user to 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'
Copy the code

__dir__ method

This method returns a list of all the member names of a class or object, not very much.

Property access order

Finally, I give you the order of property access, for your reference to learn.

  • __getattribute__
  • Data descriptor
  • Properties of the current object
  • Attributes of a class
  • Non-data descriptor
  • Attributes of the parent class
  • __getattr__

That’s it for today. See you next time