SoFunction
Updated on 2024-10-29

Specific usage of Python's built-in function delattr

The delattr function is used to delete an attribute.

delattr(x, 'foobar') is equivalent to del.

grammatical

setattr Syntax: delattr(object, name)

parameters

  1. object - an object.
  2. name -- must be an attribute of the object.

English Documentation:

delattr(object, name) 

This is a relative of setattr(). The arguments are an object and a string. The string must be the name of one of the object's attributes. The function deletes the named attribute, provided the object allows it. For example, delattr(x, 'foobar') is equivalent to del .clarification:

define a class

#coding=utf-8
# class_my.py Defining Classes (New Style Classes)

# Define the class
class Person:
  # class (note: class/class methods can modify class attributes; objects cannot modify class attributes, only instance attributes)
  name = "name" # Public properties
  __adress = "adress" # private attribute (__ attribute indicates private)

  # Constructor (object creation call) (__init__ means construct)
  def __init__(self, name, address = "Earth."):
    # Instance properties
     = name # (Note: use the instance attribute when the class attribute has the same name as the instance attribute, or use the class attribute when the instance attribute has been deleted)
    self.__adress = address
    (self)

  # Deconstruct method (object destruction call) (__del__ for destruct)
  def __del__(self):
    print("Object destroyed...")

  # toString()
  def __str__(self):
    return ""

  # Instance method (this)
  def setName(self, name): # self can be any other string (this)
     = name; # Modify Instance Attributes (not automatically added)

  # Class methods (static)
  @classmethod
  def setName_cls(cls, name):
     = name # Modify class attributes

  # Static methods (tools)
  @staticmethod
  def setName_sta(name): # (Note: Parameters section)
    return name

  def getName(self):
    return 

  def setData(self):
    # Instance properties
    self.__age = 21 # Private properties
     = "Female." # Public properties

  def show(self):
    print("Hello! %s"%)
    print("Address:%s"%self.__adress) # Use your own private attributes
    self.__eat() # Use your own private methods

  def __eat(self): # Private methods
    print("eat")



# ======= Function call ======
if __name__ == "__main__":
  # - Creating Objects -
  ps = Person("LY")

  # --- calling methods ---
  # Call the instance method
  ("LY") # Instance calls Instance methods
  ()

  # Calling class methods
  Person.setName_cls("Person") # Class calls Class methods
  ps.setName_cls("Person") # Instance calls class methods

  # Call static methods ()
  print(ps.setName_sta("Per")) # Instance calls static methods
  print(Person.setName_sta("Per")) # Class calls static methods

  # --- Access to properties ---
  print(())
  print() # Access the public property values of class properties
  print() # Access the public property values of instance properties

  # --- Modify attributes ---

  # Modify instance properties
   = "123" # Modify class attributes (note: not really modifying, just creating an instance of the attribute into the object)
  del  # Delete instance attributes (note: instances cannot (non-class methods) delete class attributes, only instance attributes created in the object are deleted, class attributes remain)
  del  # Delete instance attributes (note: true deletion, not accessible after deletion)

  # Modify class attributes
   = "Person" # Modify class attributes
  Person.setName_cls("Person") # Class Call class methods Modify class properties (Note: Classes cannot call instance methods)
  ps.setName_cls("Person") # Objects Modify class properties via class methods
  del  # Delete class attributes

  # - Delete object -
  del ps
  # > Less is more! "Static methods" and "class methods/properties" of the same level can be understood as "static", static methods are suitable for toolkits, class methods/properties can be considered in the static area, ready to use, and instances need to be instantiated in order to use. (-- my personal understanding)
# ======= Function call ======

predecessor

#coding=utf-8
# class_extend.py Inheritance (new-style classes)

# --- Single inheritance ---
# Parent class
class Animal(object):

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

  def run(self):
    print("%s on the run."%)

# Subclasses
class Cat(Animal): # Inheritance (within parent write())

  def __init__(self, name, ot = ""):
    super(Cat, self).__init__(name)

  def miao(self):
    print("Meow.")



# --- Multi-inheritance ---
class Donkey: # Donkeys
  def walk(self):
    print("walk")

  def eat(self):
    print("")

class Horse: # Horses
  def run(self):
    print("run")

  def eat(self):
    print("")

class Mule(Donkey, Horse): # Mule (donkey + horse)
  pass



# === Polymorphism ====
def animalRun(animal): The # parameter receives itself and its own subclasses
  ()




# ======= Function call ======
if __name__ == "__main__":
  # - single inheritance calls -
  ani = Animal()
  ()

  cat = Cat("Cats.")
  ()
  ()


  # - multiple inheritance calls -
  mule = Mule()
  ()
  ()
  () # When there are identical methods in multiple parent classes, call the method of the top parent class (Donkey) in ().


  # - polymorphic calls -
  ani = Animal()
  animalRun(ani)

  cat = Cat("Cats.")
  animalRun(cat)
# ======= Function call ======

rewrite

#coding=utf-8
# class_rewrite.py Rewrite (new-style class)

class Animal(object):

  def run(self):
    print("")

  def eat(self, food = "Food."):
    print("eat:%s"%food)


class Cat(Animal):

  # The child class overrides the parent class's methods
  def run(self):
    print("")

  def eat(self):
    # Call methods of the parent class
    super(Cat, self).eat("Cat food.")



# ======= Function call ======
if __name__ == "__main__":
  ani = Animal()
  ()
  ()
  cat = Cat()
  ()
  ()
# ======= Function call ======

property method

#!/usr/bin/env python
# coding=utf-8
__author__ = 'Luzhuo'
__date__ = '2017/5/13'
# class_propertiemethod.py Property methods
# Attribute Methods: Turning Methods into Static Properties


# Write 1
class PM_1(object):
  def __init__(self):
    self.__name_str = "PropertieMethod_1"

  # Get
  @property
  def name(self): # Note that the method names are the same
    return self.__name_str

  # Settings
  @
  def name(self, name):
    self.__name_str = name

  # Delete
  @
  def name(self):
    del self.__name_str


if __name__ == "__main__":
  pm = PM_1()
  print()
   = "PM"
  print()
  del 
  # print()

# ==========================================================


# Write 2
class PM_2(object):
  def __init__(self):
    self.__name_str = "PropertieMethod_2"

  # Get
  def getname(self):
    return self.__name_str

  # Settings
  def setname(self, name):
    self.__name_str = name

  # Delete
  def delname(self):
    del self.__name_str

  # property(fget=None, fset=None, fdel=None, doc=None) # Returns a property, see Built-in Functions Article property_my block code (/rozol/article/details/70603230)
  name = property(getname, setname, delname)


if __name__ == "__main__":
  p = PM_2()
  print()
   = "PM2"
  print()
  del 
  # print()

reflex (i.e. automatic reaction of organism)

#!/usr/bin/env python
# coding=utf-8
__author__ = 'Luzhuo'
__date__ = '2017/5/13'
# class_reflection.py Reflection
# Dynamically modify the state/properties/methods of a program at runtime through reflection.
How is the performance of # Python's reflection mechanism? In Android Java's reflection generates garbage and executes gc, which leads to a poor UI and low performance.
# Python's reflection performance (100 million tests): directly get property value: reflection get property value = 1:1.164 ;directly set property value: reflection set property value = 1:1.754

def setname(self, name):
   = name

class Clazz(object):
  def __init__(self):
     = "Clazz"

  def getname(self):
    return 



if __name__ == "__main__":
  c = Clazz()

  # --- Methodology ---
  if hasattr(c, "getname"):
    # Get
    method = getattr(c, "getname", None)
    if method:
      print("setname_ref: {}".format(method())) # Get the method object and execute it

  if not hasattr(c, "setname"):
    # Add
    setattr(c, "setname", setname) # Add method
    method = getattr(c, "setname", None)
    if method:
      method(c, "Reflection")
    print("setname_raw: {}".format(()))

  if hasattr(c, "setname"):
    # Delete
    delattr(c, "setname")
    # (c, "Demo")


  # --- Attributes ---
  if not hasattr(c, "age"):
    # Add
    setattr(c, "age", 21) # Add method
    var = getattr(c, "age", None)
    print("age_ref: {}".format(var))
    print("age_raw: {}".format())

  if hasattr(c, "age"):
    # Get
    var = getattr(c, "age", None)
    print("age_ref: {}".format(var))

  if hasattr(c, "age"):
    # Delete
    delattr(c, "age")
    # print("age_raw: {}".format())

documentation note

#!/usr/bin/env python
# coding=utf-8
__author__ = 'Luzhuo'
__date__ = '2017/5/13'
# class_doc.py Documentation Comments
# Documentation commenting

class Foo(object):
  '''
  This is a class
  '''

  def method(self, data):
    '''
    This is a method
    :param data: the data needed
    :return: the data to be returned
    '''
    return "method"


def func(data):
  '''
  This is a function
  :param data: the required data
  :return: the data to be returned
  '''
  return "func"



if __name__ == "__main__":
  # Print the document
  print(Foo.__doc__)
  print(Foo().method.__doc__)

  print(func.__doc__)

Principles of class creation

#!/usr/bin/env python
# coding=utf-8
__author__ = 'Luzhuo'
__date__ = '2017/5/13'
# class_origin.py Origin of classes
# Classes are generated by type class instantiations, and types are generated by the interpreter.

age = 21

def __init__(self):
   = "origin"

def getname(self):
  return 

def setname(self, name):
   = name

def delname(self):
  del 


if __name__ == "__main__":
  # Create classes with type (class name, base class tuple, class member dictionary)
  Foo = type('Foo', (object,), {'__init__' : __init__, "getname" : getname, "setname" : setname,
                 "delname": delname, "age" : age})
  # Instantiate the class
  f = Foo()
  # Use
  print()
  print(())
  ("ClassOrigin")
  print(())
  ()
  # print(())

# ==================================================================================





# Metaclasses (type creation class principle)
# The metaclass is the class that creates all classes, which in Python is the type class (note that classes are also objects, and are created, i.e., everything is an object), and here's a demonstration of what the type class does

# __call__ calls (__new__ is called before __init__, when is __call__ called?)
class Foobar(object):
  def __call__(self, *args, **kwargs):
    print("Foobar __call__")

if __name__ == "__main__":
  fb = Foobar()
  fb() # The __call__ attribute is only invoked at this time

  Foobar()() # Equivalent to the way

# ------


# metaclass specifies who the class is created by
# Python looks for the __metaclass__ attribute when creating a class, (including the parent class) and if it doesn't find it, it uses the built-in metaclass type
class MyType(type):
  def __init__(self, *args, **kwargs):
    print("MyType __init__")

  def __call__(self, *args, **kwargs):
    print("MyType __call__")
    obj = self.__new__(self)
    self.__init__(obj, *args, **kwargs)
    return obj

  def __new__(cls, *args, **kwargs):
    print("MyType __new__")
    return type.__new__(cls, *args, **kwargs)


class Foo(object, metaclass=MyType): # (write) metaclass is used to create classes, Python looks for the __metaclass__ attribute when creating a class, (including the parent class) and if it doesn't find it, it uses the built-in metaclass type

  # __metaclass__ = MyType # Writes

  def __init__(self):
    print("Foo __init__")

  def __new__(cls, *args, **kwargs): # Used to instantiate objects
    print("Foo __new__")
    return object.__new__(cls) # Must be a return

  def show(self):
    print("Foo show")


if __name__ == "__main__":
  print("start")
  f = Foo()
  ()
  # MyType __new__ => MyType __init__ => 'start' => MyType __call__ => Foo __new__ => Foo __init__ => 'Foo show'

Some other additions

#!/usr/bin/env python
# coding=utf-8
__author__ = 'Luzhuo'
__date__ = '2017/5/13'
# class_other.py Some additions about classes


class Demo(object):
  def show(self):
    print("Demo show")

if __name__ == "__main__":
  # __module__ The module name of the object.
  # __class__ The object's class object
  print(Demo.__module__) # The module name of this object => __main__
  print(Demo.__class__) # Class object for this object => <class 'type'>

  obj = Demo()
  print(obj.__module__) # The module name of this object => __main__
  print(obj.__class__) # Class object for this object => <class '__main__.Demo'>
  obj.__class__.show(obj) # Class objects can be used

  # ============================

  # __dict__ All members of a class or object
  print(Demo.__dict__) # Class Attributes
  print(obj.__dict__) # Instance properties

This is the whole content of this article.