Python Advanced (16) – Special Methods of Class Objects (3)

Original link: https://chegva.com/5307.html

◎Knowledge points

  1. The special method of class object __del__()

  2. The special method of class object __getattr__()

  3. The special method of class object __getitem __ ()

  4. The special method of class object __call__()

◎Script practice

The special method of class object __del__()

 """One, the special method of class object __del__()"""  """ Objects that are no longer needed are automatically destroyed by the system to free memory. Therefore, there is usually no need to manually perform cleanup when objects are destroyed. However, when using our own created resources, some additional cleanup may need to be performed, for example, if a custom class object is created to open a file and write some data, it may need to be closed before the instance object is destroyed The document. To perform this extra cleanup, the special method __del__() can be implemented in the custom class object When an object in memory is destroyed (garbage collection), its corresponding special method __del__() is automatically called When the reference count of the object is 0, the object will not be destroyed (garbage collection) immediately, and when the garbage collection will be performed is uncertain. therefore, It is also uncertain when the special method __del__() will be called"""  class MyClass(object): def __del__(self): print("The special method __del__ was called")  mc = MyClass() del mc # special method __del__ is called 

The special method of class object __getattr__()

 """Second, the special method of class object __getattr__()"""  """ When accessing an attribute or method of an instance object, if the specified attribute or method does not exist, an AttributeError will be thrown """  class MyClass(object): pass  mc = MyClass()  # print(mc.data) # AttributeError: 'MyClass' object has no attribute 'data' # mc.do_sth() # AttributeError: 'MyClass' object has no attribute 'do_sth'  """ When accessing an attribute or method of an instance object, in order to avoid throwing an AttributeError when the specified attribute or method does not exist, The special method __getattr__() can be implemented in the class object corresponding to the instance object. This way, when the specified property or method does not exist, The special method __getattr__() will be called automatically """  class SomeClass(object): def __getattr__(self, name): if name == "data": return 18 elif name == "do_sth": return print raise AttributeError("'SomeClass' object has no attribute '%s'" % name)  sc = SomeClass() print(sc.data) #18 sc.do_sth(1, 2, 3) # 1 2 3 # print(sc.score) # AttributeError: 'SomeClass' object has no attribute 'score' 

The special method of class object __getitem__ ()

 """Three, the special method of class object __getitem__()"""  """ For instance objects of custom objects, by default, they cannot use bracket syntax to manipulate data like lists and dictionaries """  class MyClass(object): pass  mc = MyClass() # print(mc[3]) # TypeError: 'MyClass' object is not subscriptable  """ If you want the instance objects of the custom class object to be like lists and dictionaries, use the bracket syntax to manipulate data, The following special methods must be implemented in the custom class object: 1. __getitem__(self, key)  When the operation obj[key] is performed, this special method is automatically called 2. __setitem__(self, key, value) When the operation obj[key] = value is performed, this special method is automatically called 3. __delitem__(self, key) When the operation del obj[key] is performed, this special method """ is automatically called  class MyDict(object): def __init__(self): self.data = {}  def __getitem__(self, key): return self.data[key]  def __setitem__(self, key, value): self.data[key] = value  def __delitem__(self, key): del self.data[key]  md = MyDict()  md["one"] = 18 md["two"] = 32 print(md.data) # {'one': 18, 'two': 32}  print(md["two"]) # 32  del md["two"] print(md.data) # {'one': 18} 

The special method of class object __call__()

 """Fourth, the special method of class object __call__()"""  """ If the special method __call__() is implemented in the class object, then the instance object of the class object can be called directly like a function, and the special method __call__() will be automatically called """  class MyClass(object): def __call__(self, *args, **kwargs): print(args, kwargs)  mc = MyClass() mc() mc(1, 2, x = 3, y = 4)  """ The built-in function callable is used to determine whether the specified object is callable. In addition to the function object being callable, for the class object that implements the special method __call__(), its instance object is also callable"""  print(callable(print)) # True  def do_sth(): pass  print(callable(do_sth)) # True  print(callable(MyClass())) # True

◎Script address: https://github.com/anzhihe/learning/blob/master/python/practise/learn-python/python_advanced/special_methods3.py

This article is reprinted from: https://chegva.com/5307.html
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment