1. Modifiers for class members
All members of a class have been described in detail in the previous step. There are two forms of members of each class:
Public members, accessible anywhere
Private member, can only be used inside the class
Private members and public members are defined differently: when private members are named, the first two characters are underscores. (except for special members, such as: "init", "call", "dict", etc.)
class C: def __init__(self): self.name = 'Public field' self.__foo = "Private field"
Access restrictions for private and public members are different:
1.1 static fields
Public static fields: accessible within a class; accessible within a class; accessible in a derived class
Private static fields: accessible only within the class
Public static fields:
class C: name = "Public static field" def func(self): print C.name class D(C): def show(self): print C.name C.name # Class access obj = C() obj.func() # Class can be accessed internally obj_son = D() obj_son.show() # Accessible in derived classes
Private static fields:
class C: __name = "Public static field" def func(self): print C.__name class D(C): def show(self): print C.__name C.__name # Class access ==> error obj = C() obj.func() # Class can be accessed internally ==> Correct obj_son = D() obj_son.show() # Accessible in derived classes ==> error
1.2 general fields
Public common fields: objects can be accessed; classes can be accessed internally; derived classes can be accessed
Private common field: only accessible within the class
If you want to force access to private fields, you can access them through [object. Class name. Private field description] (for example, obj. C. foo). It is not recommended to force access to private members.
Public common fields:
class C: def __init__(self): self.foo = "Public field" def func(self): print self.foo # Class internal access class D(C): def show(self): print self.foo # Access in derived classes obj = C() obj.foo # Access through objects obj.func() # Class internal access obj_son = D(); obj_son.show() # Access in derived classes
Private common field:
class C: def __init__(self): self.__foo = "Private field" def func(self): print self.foo # Class internal access class D(C): def show(self): print self.foo # Access in derived classes obj = C() obj.__foo # Access through objects ==> error obj.func() # Class internal access ==> Correct obj_son = D(); obj_son.show() # Access in derived classes ==> error
Methods and properties are accessed in the same way as above, that is, private members can only be used inside a class
If you have to access the private property, you can use the object. Class. Property name
2. Special members of class
We introduced Python's class members and member modifiers earlier, so that we can understand that there are three class members in the class: fields, methods and properties. If there are two underscores in front of the member name, it means that the member is a private member, and the private member can only be called from within the class. No matter people or things often do not play according to routines, so do Python class members. There are some members with special meanings. Details are as follows:
2.1 __doc__
Represents the description of a class
class Foo: """ Describe class information, which is a magic for watching movies """ def func(self): pass print Foo.__doc__ #Exporting: description information for a class
2.2 module and class__
__Module indicates which module the current operation object is in
__Class? Indicates the class of the object under current operation
lib/aa.py:
#!/usr/bin/env python # -*- coding:utf-8 -*- class C: def __init__(self): self.name = 'wupeiqi'
index.py:
from lib.aa import C obj = C() print obj.__module__ # output lib.aa,Namely: output module print obj.__class__ # output lib.aa.C,Namely: output class
2.3 __init__
class Foo: def __init__(self, name): self.name = name self.age = 18 obj = Foo('wupeiqi') # Automatic execution of __init__ Method
2.4 __del__
Destruct method that automatically triggers execution when an object is released in memory.
Note: this method generally does not need to be defined, because Python is a high-level language, programmers do not need to care about the allocation and release of memory when using it, because this work is performed by the Python interpreter, so the call of the destructor is automatically triggered by the interpreter when garbage collection.
class Foo: def __del__(self): pass
2.5 __call__
Object to trigger execution.
Note: the execution of the construction method is triggered by the creation object, that is: object = class name (); the execution of the call method is triggered by the parenthesis after the object, that is: object () or class () ()
class Foo: def __init__(self): pass def __call__(self, *args, **kwargs): print '__call__' obj = Foo() # implement __init__ obj() # implement __call__
2.6 __dict__
All members of a class or object
As we know above, ordinary fields of a class belong to objects; static fields and methods of a class belong to classes, namely:
class Province: country = 'China' def __init__(self, name, count): self.name = name self.count = count def func(self, *args, **kwargs): print 'func' # Get the members of the class, that is, static fields, methods print Province.__dict__ # Output:{'country': 'China', '__module__': '__main__', 'func': <function func at 0x10be30f50>, '__init__': <function __init__ at 0x10be30ed8>, '__doc__': None} obj1 = Province('HeBei',10000) print obj1.__dict__ # Get object obj1 Members # Output:{'count': 10000, 'name': 'HeBei'} obj2 = Province('HeNan', 3888) print obj2.__dict__ # Get object obj1 Members # Output:{'count': 3888, 'name': 'HeNan'}
2.7 __str__
If the str method is defined in a class, the return value of the method is output by default when the object is printed.
class Foo: def __str__(self): return 'wupeiqi' obj = Foo() print obj # Output: wupeiqi
2.8 __getitem__,__setitem__,__delitem__
Used for index operations, such as dictionaries. The above means to obtain, set and delete data respectively
#!/usr/bin/env python # -*- coding:utf-8 -*- class Foo(object): def __getitem__(self, key): print '__getitem__',key def __setitem__(self, key, value): print '__setitem__',key,value def __delitem__(self, key): print '__delitem__',key obj = Foo() result = obj['k1'] # Auto trigger execution __getitem__ obj['k2'] = 'wupeiqi' # Auto trigger execution __setitem__ del obj['k1'] # Auto trigger execution __delitem__
2.9 __getslice__,__setslice__,__delslice__
The three methods are used for slicing operation, such as list
#!/usr/bin/env python # -*- coding:utf-8 -*- class Foo(object): def __getslice__(self, i, j): print '__getslice__',i,j def __setslice__(self, i, j, sequence): print '__setslice__',i,j def __delslice__(self, i, j): print '__delslice__',i,j obj = Foo() obj[-1:1] # Auto trigger execution __getslice__ obj[0:1] = [11,22,33,44] # Auto trigger execution __setslice__ del obj[0:2] # Auto trigger execution __delslice__
2.10 __iter__
For iterators, the reason that lists, dictionaries, and tuples can be used in for loops is that "iterator" is defined inside the type
Step one:
class Foo(object): pass obj = Foo() for i in obj: print i # Report errors: TypeError: 'Foo' object is not iterable
The second step:
#!/usr/bin/env python # -*- coding:utf-8 -*- class Foo(object): def __iter__(self): pass obj = Foo() for i in obj: print i # Report errors: TypeError: iter() returned non-iterator of type 'NoneType'
The third step:
#!/usr/bin/env python # -*- coding:utf-8 -*- class Foo(object): def __init__(self, sq): self.sq = sq def __iter__(self): return iter(self.sq) obj = Foo([11,22,33,44]) for i in obj: print i
As can be seen from the above steps, for loop iteration is actually iter([11,22,33,44]), so the execution process can be changed to:
#!/usr/bin/env python # -*- coding:utf-8 -*- obj = iter([11,22,33,44]) for i in obj: print i
Inside the for loop syntax:
#!/usr/bin/env python # -*- coding:utf-8 -*- obj = iter([11,22,33,44]) while True: val = obj.next() print val
2.11 new and metaclass__
Read the following code:
class Foo(object): def __init__(self): pass obj = Foo() # obj It is through Foo Class instantiated object
In the above code, obj is an object instantiated by Foo class. In fact, not only obj is an object, but Foo class itself is also an object, because everything in Python is an object.
If according to the theory that everything is an object: obj object is created by executing the construction method of Foo class, then the Foo class object should also be created by executing the construction method of a class.
print type(obj) # Output:<class '__main__.Foo'> Express, obj Object by Foo Class creation print type(Foo) # Output:<type 'type'> Express, Foo Class object type Class creation
Therefore, obj object is an instance of Foo class, and Foo class object is an instance of type class, that is, Foo class object is created by the construction method of type class.
There are two ways to create a class:
1. Common way
class Foo(object): def func(self): print 'hello xiaohuihui'
2. Special method (constructor of type class)
def func(self): print 'hello wupeiqi' Foo = type('Foo',(object,), {'func': func}) #type First parameter: class name #type Second parameter: base class of current class #type Third parameter: members of the class
Class is generated by type class instantiation
Then the problem comes. By default, a class is generated by instantiation of a type class. How to create a class in a type class? How do classes create objects?
Answer: there is an attribute \\\\\\\\\\\\\\\.
class MyType(type): def __init__(self, what, bases=None, dict=None): super(MyType, self).__init__(what, bases, dict) def __call__(self, *args, **kwargs): obj = self.__new__(self, *args, **kwargs) self.__init__(obj) class Foo(object): __metaclass__ = MyType def __init__(self, name): self.name = name def __new__(cls, *args, **kwargs): return object.__new__(cls, *args, **kwargs) # First stage: interpreter executes code creation from top to bottom Foo class # Phase II: Adoption Foo Class creation obj object obj = Foo()