Python limits of 8.20 dynamically defined white list instance attributes: __ slots__

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

I. Introduction
accordance with the "instance variables defined in § 7.10 Python class", "Section 7.14 Python example of a method of parsing class" the introduction, when a class is defined, and after creating the instance of that class, you can dynamically add properties and methods to any of the examples. But in fact, Python classes in which properties can be controlled to increase, this would be analogous to a dynamic increase white list properties. The white list is defined __slots__ special instance variables in the class.
Two, slots
__slots__ is the particular object class variable is not defined, and therefore must be used if the custom class defined separately, and must be a class variables, instance variables can not be. The conventional definition syntax:
slots = (variable name 1, variable name 2, ...)
slots = [variable name 1, variable name 2, ...]
...

Since __slots__ a class variable, is best defined on the body of the class code, which may be a number of variables to a plurality. With the first embodiment, when the variable is one when, __ slots__ string type itself, when the variable is plural, it is the tuple type; the use of the second embodiment, the class type of the variable __slots__ list. Indeed __slots__ be assigned to a string, or character sequence iterables instance variable names used by the configuration, a string may be any non-iterative object can be assigned to slots . Mapping can also be used in this way not to proceed with the assignment of each presentation.
Three, __slots__ role

  1. slots allows developers to explicitly declare defines data members (e.g., feature attributes), members of the dynamic prohibited undeclared added;
  2. The slots will be reserved space for a declared variable, and stop automatically created for each instance of dict and __weakref_ special variables (except in the slots explicit statement or available in the parent class).
  1. When an undefined inherited from slots when the class, instance dict and weakref properties are always accessible;
  2. No dict variable, instances can not not give in slots listed in the definition of a new variable assignment. Try to give a variable name is not listed in the assignment would lead to AttributeError. Need to dynamically assign new variable, it is necessary to ' dict ' is added to the slots string declared in the sequence.
  3. If not set for each instance weakref variable that defines the slots of the class does not support its weak references practical. If you need to support weak reference, it is necessary to ' weakref ' was added to the slots declared string sequence.
  1. Use __slots__ compared to the use dict way can significantly save space. Attribute lookup speed is significantly improved can be obtained;
  2. slots declaratory and is not limited to class that defines it. Declared in the parent class slots also be used in its subclasses. However, the sub-category will receive dict and weakref unless they also define slots (which should contain only a statement of the position of any additional names).
  3. Non-empty slots do not apply to derived from "variable length" type, for example, derived classes built int, bytes and a tuple;
  4. __ slots__ body can only be assigned a class code, the assignment:
  1. Class can not be used in vitro "instance name .__ slots__" mode re-assignment, Python will report the read-only property;
  2. In the example method can not be used in vitro and class code "class name .__ slots__" mode assignment, the assignment will not be given, but __ slots__ ineffective, as described in Example __dict__ automatically created, if the class body __slots__ it had been defined, in the modified example __slots__ methods may be modified, but still only __ slots__ Python class body defined attributes defined added.
  1. __ after slots__ defined, if the definition of the instance variable __ slots__ outer code, an error message will AttributeError;
  2. After __ slots__ defined, in the example of the constructor method can not containing a new instance variables defined outside the other __ slots__.

Four, three cases

  1. Source code is as follows:
    # Case 1: Example # methods to define class variables Vehicle .__ slots__ no effect
class Vehicle(): 
   def __init__(self,power):
       self.power = power
       Vehicle.__slots__ = ['power']
v=Vehicle('人力')
v.wheelcount=4 #加一个实例变量不会拦截
v.__dict__  #服务字典中的自定义属性成功

Case # 2: # class using the body to define a class variable __slots__ can function properly

class Vehicle(): 
   __slots__ = ['power']
   def __init__(self,power):
       self.power = power
       
v=Vehicle('人力')
v.wheelcount=4 #加一个实例变量会拦截
v.__dict__  #没有字典属性      

Case # 3: # Class variables defined in the class __slots__ vitro modification, but can be modified to modify ineffective

class Vehicle(): 
   __slots__ = ['power','weight']
   def __init__(self,power):
       self.power = power
       
v=Vehicle('人力')
Vehicle.__slots__ = ['wheelcount','oilcost']
Vehicle.__slots__ #显示赋值被修改
v.wheelcount=4 #加一个实例变量会拦截
v.__dict__  #没有字典属性
  1. Perform a screen shot:

This section describes the definition and use of special precautions __slots__ variables and example have been described, it is understood by the description, __ slots__ whitelist is equivalent to an instance variable.

Old ape Python, with the old ape learn Python!
Blog address: https: //blog.csdn.net/LaoYuanPython

please support, thumbs up, comment and processing concern! Thank you!

Guess you like

Origin blog.csdn.net/LaoYuanPython/article/details/94890048