Iron Music Learning python_day24_ Object-oriented advanced 1_ built-in method

Source: Internet
Author: User
Tags shuffle

Iron Music Learning python_day24_ Object-oriented advanced 1_ built-in method

Topic 1: Learning method "WWWH"

What's where why?
What it is, where it is, why, how it's used

When learning a new point of knowledge, ask more than four questions above and learn and practice thoroughly.

What is reflection?

Not to mention the boring concept, you can summarize it yourself, for the reflection in Python, when will be used?
Reflection is required to use variable names of string data types when using variables.
(Manipulate object-related properties and methods in the form of strings.) )
Keywords: string
The scene used to string is more in:
1) A string is stored in the file,
2) The closest string that can be passed on the network,
3) User input (not much, because after all, there is a security risk)

Learn the use of built-in methods today

(Overriding built-in methods applied to individual requirements)

__len__  Len(obj) obj corresponds to a class that contains the __len__ method,Len(obj) to execute normally.__hash__ Hash(obj) is an object class that has only implemented the __hash__ method and has (obj) to execute properly. Off Topic2: Lists and dictionaries need to be iterated over to look for a better list than a dictionary, such as traversing a saved user name and password in a file. and need to quickly by a key to find a value, in a dictionary good, such as the user login status. __str__ built-in methods and __repr__ built-in methodsPrint()# Write to the file print for you to convert the data type to a string. PrintThe result of (obj) is obj.__str__() results.Str(obj) is also the result of obj.__str__() result (Str is a class name).'%s ' %The result of obj is also obj.__str__() results.reprThe results of (obj) and obj.__repr__() is the same.'%r ' %The results of obj and obj.__repr__() is the same. All outputs are essentially written to the text.Print(LIS)--->Lis.__str__() The __str__ in the object class is the memory address that returns a data by default. The newly-created class overrides the __str__ built-in method in its own class to allow human output. Overriding the built-in method to invoke the built-in function outputs the results you want. Reps1) and Reps (' 1 'The result of the print is different because the classintand classStrThe __repr__ method is not the same. The default design is to let you distinguish between different. When you need to use the __str__ scene, can not find __str__ to find __repr__, when you need to use the __repr__ scene, can not find __repr__ when you find the parent class repr. The double lower repr is a spare tire for the double lower Str.Len() obj.__len__() The return value is consistent rather than that: the result of Len () is dependent on obj.__len__() similarlyHash() The result is dependent obj.__has__ ()StrThe result of () is dependent on obj.__str__()PrintThe result of (obj) is dependent on obj.__str__()%The result of S is dependent on obj.__str__()reprThe result is dependent on obj.__repr__()%The result of R is dependent on obj.__repr__() repr is a spare tire for Str. Off Topic3: The syntax sugar is sweet. Any grammatical method that is convenient to you that does not appear in the form of a function call can be called a grammatical sugar. The superficial syntax is just a simple way, and actually the backstage will be implemented to the concrete method. __format__ method you need to have the Format_spec parameter when you implement the double-down format yourself. Format_spec Parameters: Formatted standard (rule), as specified by the format built-in function. Format_spec defines a standard externally, in order to make the user more flexible to customize.def format(*Args**Kwargs):# Real Signature Unknown    """Return value.__format__ (format_spec)    Format_spec defaults to the empty string    """    PassExample: Format_dict={' Nat ':'{Obj.name}-{OBJ.ADDR}-{Obj.type}',#学校名-School address-school type (default output format)    ' TNA ':'{Obj.type}:{Obj.name}:{OBJ.ADDR}',#学校类型: School Name: School Address    ' Tan ':'{Obj.type}/{OBJ.ADDR}/{Obj.name}',#学校类型/School address/School name}classSchool:def __init__( Self, NAME,ADDR,type): Self. Name=Name Self. addr=Addr Self.type=type    def __repr__( Self):return ' School (%s,%s) ' %( Self. Name, Self. addr)def __str__( Self):return ' (%s,%s) ' %( Self. Name, Self. addr)def __format__( Self, Format_spec):# if Format_spec        if  notFormat_specorFormat_spec not inchFormat_dict:format_spec=' Nat 'Fmt=FORMAT_DICT[FORMAT_SPEC]returnFmt.format(obj= Self) S1=School (' oldboy1 ',' Beijing ',' Private ')Print(' from repr: ',repr(S1))Print(' from str: ',Str(S1))Print(S1)" "str function or print function--->obj.__str__ ()repr or Interactive interpreter--->obj.__repr__ ()If the __str__ is not defined, then the __repr__ will be used instead of the outputNote: The return value of both methods must be a string or throw an exception" "Print(format(S1,' Nat '))Print(format(S1,' TNA '))Print(format(S1,' Tan '))Print(format(S1,' Asfdasdffd ')) off-topic4: Why should it be normalized?1) closer to function-oriented programming2) Simple and Save code __call__ built-in methods:classTeacher ():def __call__( Self):Print(123) T=Teacher () t () to the image name plus (), which is equivalent to invoking the built-in __call__ of the classcallableDetects whether the object can be called and returns a Boolean value. Whether an object is callable depends on whether the class that corresponds to the object implements the __call__. If the object has a built-in double-down call method, it can be called. The object is appended with parentheses to trigger execution. Note: The execution of the construction method is triggered by the creation object, namely: the object=Class name (), and for__call__The execution of a method is triggered by an object followed by parentheses, namely: Object () or Class () () __eq__ built-in method: judging==This matter is determined by the return value of __eq__.classA:def __init__( Self): Self. A= 1         Self. b= 2    def __eq__( Self, obj):if   Self. A==Obj.a and  Self. b==OBJ.B:return TrueA=A () b=A ()Print(A==b__del__destructor methods all object-oriented languages have;Do some finishing work when deleting an object, such as closing some open files, disconnecting some web links, etc. destructor, which automatically triggers execution when the object is freed in memory. 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.classA:def __init__( Self): Self. f= Open(' File ',' W ')del __del__( Self): Self. f.closePrint(' execute me. ') A=A ()delAPrint(' 666 'After running a program, the Python interpreter executes the reclaimed memory and automatically runs the double-down Del.__new__When the constructor method is instantiated, before Init Initializes, there is a process for creating objects, and the process of creating objects is to use the built-in double-bottom new method, first to bring the child to dress, first to have the object initialized. Design Patterns---Singleton mode (Double Down new method) Singleton mode is a class that can have only one instance. can be instantiated multiple times, but only one instance will eventually exist.# Use double-down new to implement the Singleton pattern as follows:classTeacher (): __instance= None    def __init__( Self, name, age): Self. Name=Name Self. Age=Agedef __new__(CLS,*Args**Kwargs):ifCls.__instance is None: obj= Object.__new__(CLS) cls.__instance=ObjreturnCls.__instancea=B' Alex ', the) b=B' Egon ', -)Print(a)Print(b)Print(A.name)Print(b.name) Item series objects are used in the form of brackets (attributes)__getitem__\__setitem__\__delitem__[] in the form of brackets, the dictionary is the way to find the value by key, through the double lower GetItem implementation__getitem__Query object name [property name] Equals object name. Property name__setitem__Set object name [property name]=Value assignment and modification, new__delitem__DeletedelThe object name [property name] is equivalent to the Del object name. The attribute is also equivalent to the execution of the __delattr__ example: Poker gameclassFranchdeck:ranks=[Str(n) forNinch Range(2, One)]+ List(' Jqka ')# Direct Stitching two lists generate 13 cards, and the elements inside are converted to strings at the same timeSuits=[' hearts ',' Block ',' Plum blossom ',' Spades ']def __init__( Self): Self. Cards=[(rank, suit) forRankinchFranchdeck.ranks forSuitinchFranchdeck.suits]# The number of points in the tuple and the color are deduced from the loop respectively        # [(' 2 ', ' hearts '), (' 2 ', ' Squares '), (' 2 ', ' Plum '), (' 2 ', ' Spades '), (' 3 ', ' hearts ' ) ...    def __len__( Self):return Len( Self. cards)# 52 Statistics Poker Cards    def __getitem__( Self, item):return  Self. Cards[item]# equal to the list slice, take out the elements    def __setitem__( Self, key, value): Self. Cards[key]=Valuedeck=Franchdeck ()# instantiation# Take a value for the list object slice, the next two lines are the samePrint(deck[0])Print(Deck.__getitem__(0))Print(deck.ranks)Print(deck.cards)# for the list of statistical elements, the following two lines are the same resultPrint(Len(deck))Print(Deck.__len__())# random Poker selection fromRandomImportChoicePrint(Choice (deck))Print(Choice (deck))# Set the corresponding index position why valueDeck.__setitem__(0, (' 3 ',' Spades ')) deck[1]=(' 3 ',' Plum blossom ')Print(deck[0])# The value is not the heart 2, it becomes the Spades 3Print(deck[1])# The value is not a block 2, it becomes a plum 3# shuffle = shuffle, but every time you have to shuffle, do not wash the words taken out of the same group fromRandomImportShuffleshuffle (Deck)Print(deck[:5]) Shuffle (deck)Print(deck[: -]) Shuffle (deck)# Shuffle, and then slice the card, will be 52 pieces in order to play pokerPrint(deck[: -])Print(deck[ -: -])Print(deck[ -: the])Print(deck[ the: the])# [(' 7 ', ' Spades '), (' A ', ' Square '), (' Q ', ' Plum '), (' 3 ', ' Plum '), (' 10 ', ' the ' box '), (' K ', ' hearts '), (' 8 ', ' Spades '), (' J ', ' the ' "), (' 2 ', ' spades ') ), (' 5 ', ' Square '), (' Q ', ' Square '), (' 5 ', ' hearts '), (' 9 ', ' Hearts ')]# [(' J ', ' Plum '), (' Q ', ' hearts '), (' 3 ', ' hearts '), (' 4 ', ' Plum '), (' 10 ', ' Spades '), (' 10 ', ' Plum '), (' K ', ' Spades '), (' 7 ', ' hearts '), (' 2 ', ' plum '), (' A ', ' Plum '), (' J ', ' Spades '), (' 2 ', ' Square '), (' 3 ', ' Spades ')]# [(' 7 ', ' Plum '), (' K ', ' blocks '), (' 6 ', ' hearts '), (' J ', ' hearts '), (' A ', ' hearts '), (' A ', ' ' Heart '), (' 4 ', ' Blocks '), (' 8 ', ' ' "') ', (' 4 ', ' Spades '), , (' 9 ', ' Spades '), (' 3 ', ' Square '), (' Q ', ' Spades '), (' 8 ', ' hearts ')]# [(' 4 ', ' hearts '), (' 9 ', ' Plum '), (' 9 ', ' Block '), (' 6 ', ' the ' Block '), (' A ', ' Spades '), (' 6 ', ' Plum '), (' 10 ', ' hearts '), (' 6 ', ' Spades '), (' K ', ' Plum ') ), (' 5 ', ' Spades '), (' 7 ', ' Square '), (' 2 ', ' hearts '), (' 8 ', ' Plum ')]Interview questions: -Objects of the same class, the person object has the same name, the same gender, but different ages, to go to the weight.classPerson:def __init__( Self, Name,age,sex): Self. Name=Name Self. Age=Age Self. Sex=Sexdef __hash__( Self):return Hash( Self. Name+ Self. Sex)def __eq__( Self, other):if  Self. Name==Other.name and  Self. Sex==Other.sex:return TrueP_lst=[] forIinch Range( -): P_lst.append (Person (' Egon 'I' Male '))Print(P_LST)Print(Set(P_LST))

End
2018-4-19

Iron Music Learning python_day24_ Object-oriented advanced 1_ built-in method

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.