The path to Python (26th) object-oriented advanced: Built-in methods

Source: Internet
Author: User
Tags exception handling

First, __getattribute__ object.__getattribute__(self, name)

is called unconditionally, accessing properties through an instance. If the class is defined __getattr__() , it __getattr__() will not be called (unless the call is displayed or the Attributeerror exception is thrown)

  
  Class Foo:  ?      def __init__ (self,x):          self.x = x  ?      def __getattr__ (self, item):          print ("Execute __getattr__")  ?      def __getattribute__ (self, item):          print ("Execute __getattribute__")          # Raise Attributeerror ("non-existent exception")  ?  f = Foo ("Nick")  print (f.x)  print (f.xxxx) #这里本来调用后应该在__getattribute__中产生AttributeError, and then call __getattr__, But in # here __getattribute__ is rewritten, no attributeerror is generated, so there is no call __getattr__

  

Output results

    Execute __getattribute__  None  execution __getattribute__  

  

object.__getattr__(self, name)

When attribute is not found in the general position, GetAttr is called, returning a value or Attributeerror exception.

  
  Class Foo:  ?      def __init__ (self,x):          self.x = x  ?      def __getattr__ (self, item):          print ("Execute __getattr__")  ?      # def __getattribute__ (self, item):      #     print ("Execute __getattribute__")          # Raise Attributeerror ("non-existent exception")  ?  f = Foo ("Nick") print (  f.x)  print (f.xxxx) #这里是执行了新定义的__getattr__方法 with no direct error

  

Output results

  
  Nick,  execute __getattr__.  

  

Every time A property is accessed through an instance, it goes through the __getattribute__ function. When a property does not exist, it still needs to be accessed __getattribute__ , but it is then accessed __getattr__ . This is like an exception handling function. It is important to note that when you use a class to access a variable that does not exist, it does not pass through the __getattr__ function.

When the property is present, the __getattribute__ value of the property is returned through the function.

Second, __setitem__,__getitem,__delitem__

In a class, when an object accesses a property or method in the form of a object["key", a built-in method of the item series is called, and the object is called with the attr series built-in method when the property or method is called in the form of a point.

  
  Class Foo:  ?      def __init__ (self,name):          self.name = name  ?      def __getitem__ (self, item):          print ("Execute __getitem__")          return Self.__dict__[item]  ?      def __setitem__ (self, Key, value):          print ("Execute __setitem__")          Self.__dict__[key] = value  ?      def __delitem__ (self, key):          print ("Execute __delitem__")          Self.__dict__.pop (key)  ?  f = Foo ("Nick")  print (f["name"])  #获取属性, execute __getitem__ method  f["Age" =  #设置属性, execute __setitem__ method  print (f.__dict__)  del f["name"]  #删除属性, execute __delitem__ method  print (f.__dict__)

  

Output results

    Execution __getitem__  Nick  executes __setitem__  {' name ': ' Nick ', ' age ':  18} Execute __delitem__  {' Age ':

  

iii. __str__,__repr__ , __format__

__str__is to control the display of strings that change objects

At the print(obj)/‘%s‘%obj/str(obj) time, is actually the internal calling 了obj.__str__ method, if the Str method has, then he must return a string, if there is no __str__ method, will first find the class in the __repr__ method, and no longer find the parent class (object) __str__ .

Example 1

  Class Foo:      def __str__ (self):          return "Controlling the display of objects when printing"  ?  f = Foo ()  print (f) #输出结果:  controls the display when printing objects

  

Analysis: Here the printed object calls the redefined __str__ method directly

Example 2

  Class Foo:      def __str__ (self):          return "Controlling the display of objects when printing"  ?  f = Foo ()  a = str (f)  print (a) #输出结果:  controls the display form when printing objects

  

Analysis: Here the str (object) is also called the __str__ method

Example 3

  
  Class Foo:      def __str__ (self):          return "Controlling the display of objects when printing"  ?  f = Foo ()  print ("%s"%f) #输出结果:  controls the display form when printing objects

  

Analysis: The "%s"%f here also calls the __str__ method

__repr__is also the name of the display object, the method is called with Repr (object) or "%r"%object __repr__

REPR is the spare tire of STR, but STR cannot do repr spare tire

Example 4

  Class Foo:  ?      def __str__ (self):          return "Controlling the display form when printing objects"  ?      def __repr__ (self):          print ("in Execution repr")          return "repr foo"      pass  f = foo ()  print ("%r"%f)   Print (f)

  

Output results

  
    display form when executing repr repr Foo  controls the printing of objects

  

Analysis: Here print ("%r"%f) calls the redefined __repr__ method, and print (f) invokes the __str__ method

Example 5

  
  Class Foo:  ?      def __str__ (self):          return "Controlling the display form when printing objects"  ?      def __repr__ (self):          print ("in Execution repr")          return "repr foo"      pass  f = foo ()  

  

Output results

  In the execution repr  repr Foo

  

Example 6

  
  Class Foo:  ?      # def __str__ (self):      #     Return "control the display form when printing objects"  ?      def __repr__ (self):          print ("in Execution repr")          return "repr foo"      pass  f = foo ()  print (f)

  

Output results

    In the execution repr  repr Foo

  

Analysis: If you want to call the __str__ method, first in this class to find there is no method, if there is __str__ no way to find this class, __repr__ If there is a method of execution __repr__ , The method of the parent class is no longer borrowed __str__ . So repr is the spare tire of STR, but STR can not do repr spare tire.

Example 7

  
  Class Foo:  ?      def __str__ (self):          return "Controlling the display form when printing objects"  ?      # def __repr__ (self):      #     print ("in Execution repr")      #     return "repr foo"      pass  f = foo ()  print (Repr (f)) #输出结果 <__main__. Foo Object at 0x002eb550>

  

Analysis: To invoke a __repr__ method, this class does not, directly borrowing the method of the parent class, without __repr__ executing the __str__ method. So repr is the spare tire of STR, but STR can not do repr spare tire.

__format__

Self-Customizing formatted strings __format__ ,

    Format_dic = {      "Ymd": "{0.year}{0.month}{0.day}",      "dmy": "{0.day}:{0.month}:{0.year}",      "mdy": "{0.month }-{0.day}-{0.year} "  }  ?  Class Foo:  ?      def __init__ (self,year,month,day):          self.year = year          self.month = month          Self.day = Day  ?      def __format__ (self, format_spec):          If isn't format_spec or Format_spec not in format_dic:              format_spec = "Ymd" 
   FMT = Format_dic[format_spec]          return Fmt.format (self)  ?  f = Foo (2018,8,20) (Format (f)) print (Format (f  , "dmy")) print (  format (f, "MDY")) print (  "{: MDY} ". Format (f))

  

Output results

  
  2018820  20:8:2018  8-20-2018  8-20-2018

  

Parse: Call the Format method to customize the string formatting, where the __format__ method is called

Four, __slots__

__slots__: In fact, the name in the class is locked, instantiated objects, can only be assigned and called, can not delete properties and add new properties

1, __slots__ What: is a class variable, the value of a variable can be a list, a meta-ancestor, or an iterative object, or a string (meaning that all instances have only one data property)

2, using the point to access the nature of the property is to access the class or object's __dict__ Property Dictionary (the Dictionary of the class is shared, and each instance is independent)

3, the dictionary will occupy a lot of memory, if you have a few properties of the class, but there are many instances, in order to save memory can be used to __slots__ Replace the instance __dict__ when you define __slots__ , __slots__ A more compact internal representation is used for the instance. Instead of defining a dictionary for each instance, the instance is constructed from a small, fixed-size array, similar to a tuple or list. The __slots__ attribute names listed in are internally mapped to the specified small label for this array. The use of __slots__ a bad place is that we can no longer add new properties to the instance, only __slots__ those attribute names defined in.

4, Application scenario: When the tens of thousands of objects are instantiated, each object will generate a namespace __dict__ , and each namespace will occupy a memory, resulting in a waste of memory, use __slots__ , no longer produce the dict of each object , the dict of the object are unified with the dict of the class, and the attributes are defined by slots.

  
  Class Foo:  ?      __slots__ = ["Name", "Age"]  #在类中定义属性 "name" and "Age"  ?  F1 = Foo ()  f1.name = "Nick" #首先要进行赋值, no assignment call error  print (f1.name)  # f1.gender = "female"  # added __slots__ Other than the property will error  # del f1.age   #删除属性也会报错

  

Five, __doc__

__doc__The document comment information is displayed, and the document comment information cannot be inherited to the child class.

Example

  
  Class Foo: "" "      I am a document comment      " "      pass  ?  f = Foo ()  print (f.__doc__) #输出结果:    I am a document comment

  

Example 2

  
  Class Foo: "" "      I am a document comment      " "      pass  ?  Class Son (Foo):      pass  ?  s = Son ()  print (s.__doc__)  

  

VI, __module__ and __class__

 __module__Object that represents the current operation in that module

  __class__What is the class of the object that represents the current operation

Example 1

  
  Class Foo:  ?      def __init__ (self,name):          self.name = name  ?  f = Foo ("Nick")  print (f.__module__) #当执行文件为当前文件时, __module__ = __main__  #输出结果: __main__  Print (f.__class__ )  #输出当前操作的类名是什么  #输出结果: <class ' __main__. Foo ' >

  

Example 2

File structure

  ├──index.py #执行文件
│├──test
│ │├──a.py

a.py content:

  
  Class Bar:      def __init__ (self):          self.name = "Nicholas"

  

index.py content:

From test.a import  Bar  ?  Class Foo:  ?      def __init__ (self,name):          self.name = name  ?  b = Bar ()  print (b.name)  #输出结果 Nicholas  Print (b.__module__)  #输出结果 test.a, which indicates that the class of the current operation is under  test.a Print (b.__class__)  

  

vii. __del__ methods of destruction

destructor, which automatically triggers execution when the object is freed in memory. That is, the method of freeing memory is cleared.

This is the method that triggers execution when the instantiated object is recycled, and deleting the object's properties does not trigger the __del__ method

Note: This method is generally not defined because Python is a high-level language, and programmers do not need to be concerned with allocating and releasing memory because this work is done by the Python interpreter, so the destructor calls are automatically triggered by the interpreter when it is garbage collected.

Example 1

  
  Class Foo:      def __init__ (self,name):          self.name = name  ?      def __del__ (self):          print ("I'm done!") ")  ?  f = Foo ("Nick")  print ("-----1")  del f.name  print ("-----2")   #这里是先执行print ("-----1") then execute print ("- ----2 "),  # execution del f.name just deletes the" name "property of the object dictionary and does not trigger the __del__ method

  

Output results

  
  -----1  -----2  I'm done!

  

Example 2

  
  Class Foo:      def __init__ (self,name):          self.name = name  ?      def __del__ (self):          print ("I'm done!") ")  ?  f = Foo ("Nick")  print ("-----1")  del F   #删除对象才能调用__del__, where both the __del__ method is executed and the object print is deleted  ("-----2")   

  

Output results

    -----1  I'm done!  

  

Example 3

  
  Class Foo:      def __init__ (self,name):          self.name = name  ?      def __del__ (self):          print ("I'm done!") ")  ?  f = Foo ("Nick")  Import Time  time.sleep (2)

  

Output results

I'm doing it!

  

Analysis: Here at the end of the program, the Python interpreter automatically reclaims the memory and executes the __del__ method

Typical application scenarios:

Create a database class, instantiate the database link object with the class, the object itself is stored in the user space memory, and the link is managed by the operating system, stored in kernel space memory

When the program ends, Python will only reclaim its own memory space, that is, user-state memory, and the operating system's resources are not recycled, which requires us to customize __del__ , before the object is deleted to the operating system to shut down the database link system calls, recycling resources.

Example

  
  Class Foo:  ?      def __del__ (self):          print ("I executed")  ?  f = Foo ()  f.file  = open ("test.txt")   #打开文件, open a file in the operating system,  # got the file operator exists in memory  del f.file   # Deleted the in-memory file operator, but did not close the file in the operating system,  # You need to add a custom f.file.close () to the __del__ to close the operating system's file  print ("-----1")  # The last program ends the Python interpreter automatically performs a memory recovery and executes the __del__ method

  

Output results

    -----1  

  

The path to Python (26th) object-oriented advanced: Built-in methods

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.