I. Yesterday's content review
1. Reflection
The variable that operates the namespace with the name of the string type.
Reflection usage Scenario: the obvious simplification of the code, can get the variable name is a string type of time,
User input, file read-in, on-line transmission
2.__call__
The __call__ method is called by the object name ()
3.__len__
4.__hash__
5.__eq__
6.__dict__
Object name. __dict__: A variable that looks at the variable of the object space,
Class name. __dict__ class Space
7.__slots__
#__slots__ = (' name ', ' age ')
8.__module__ and __class__
9.isinstance and Issubclass
Two. Summary of today's content 1.__new__
#创建一个对象, is a constructor method in the Initialize Method __init__ (self,... Executes before execution.
Single-Case mode:
classA:__instance=Nonedef __init__(self,name): Self.name=namedef __new__(CLS, *args, * *Kwargs):if notCls.__instance: CLS.__instance= object.__new__(CLS)returnCls.__instancea= A ('Alex') b= A ('Jack')Print(A.name)Print(B.name)
example of a singleton pattern
2.__del__
#在一个对象在内存中删除前, execute the __del__ method
# contrast delattr use a variable of character type to remove this variable from the namespace
# compare @property deleter masquerading as a property, to perform a delete property
#Python解释器
#能够主动回收不用的变量
#在程序结束的时候所有的数据都会被清除
#如果用户主动删除某个变量
# then this variable will be actively deleted
#无论上述哪种方式
#在删除一个变量之前都会主动的执行析构方法__del__
Application: Returning an operating system resource before an object is deleted
Class B:
def __init__ (Self,path):
SELF.F = open (path)
def __del__ (self):
Self.f.close ()
b = B (' USERINFL ')
3.__getitem__, __setitem__, __delitem__
# There are built-in methods in the built-in modules
#是依赖__getitem__方法的
#或者说是依赖item [' A '] this type of call
# Shuffle, draw example:
Random.choice method Dependency (__len__,__getitem__)
Random.shuffle method dependent objects and built-in Parties (__LEN__,__GETITEM__,__SETITEM__)
ImportRandom fromCollectionsImportNamedtuplecard= Namedtuple ('Card', ['Rank','Suit'])classfranchdeck:ranks= [I forIinchRange (2, one)] + list ('Jqka') Suits= ['Hearts','blocks','Black Peach','Plum Blossom'] def __init__(self): self.__cards= [Card (rank, suit) forRankinchFranchdeck.ranks forSuitinchFranchdeck.suits]def __len__(self):returnLen (self.__cards) def __getitem__(self, item):returnSelf.__cards[item]def __setitem__(self, Key, value): Self.__cards[Key] =valuedef __delitem__(self, key):delSelf.__cards[Key]deck=Franchdeck ()Print(Deck.__dict__)Print(Deck[0]) random.shuffle (deck)Print(Deck.__dict__)Print(Random.choice (deck))
examples of shuffling and drawing cards
4. Exception Handling
#try except
#try except Else
#try except else finally
#try finally
# Assert 1=2
# raise actively throws an exception
# Custom Exception Types
classwuexception (baseexception):def __init__(self, name): Self.__name=namedef __str__(self):returnSelf.__nameTry: RaiseWuexception ('Let's try something wrong.')exceptwuexception as E:Print(e)
examples of custom exception types
Three. Preview and expand
1. Understanding of Meta-class Metaclass:
1), the class that we created with the Class keyword is created from the base class type class:
Class Foo (object):
A = 1
def func ():
Print (6666)
Equivalent to: Type (' Foo ', (object,), {' A ': 1, ' func ': func})
def func ():
Print (6666)
2), create the class when there is a priority to find __metaclass__, and did not look for the parent class, the parent class did not find the module, has not been found to use the built-in type for class creation
Class A:
__metaclass__ = mm
3), our own custom meta-class:
Class Metaclasstest (Type):
def __new__ (cls,name,bases,dict):
..........
Return super (). __new__ (Cls,name,bases,dict (changeable))
Python full stack development day24-__new__, __DEL__, item series, exception handling