Python scattered functions

Source: Internet
Author: User
Tags instance method

1. The difference between Python json.dumps () json.dump ()

Note that cat is the content of the direct output file

 Both load and loads are implemented as "deserialization", the difference being in Python (for example):

    • Loads the python built-in data into a string for memory objects

      such as using Json.dumps serialized object D_json=json.dumps ({' A ': 1, ' B ': 2}), where D_json is a string ' {"B": 2, "a": 1} '

      D=json.loads (D_json) #{B ": 2," a ": 1}, re-deserialized to dict using load

    • Load for file handle

      If there is a JSON file locally A.json you can d=json.load (open (' A.json '))

      Accordingly, dump is to serialize the built-in type to a JSON object and write to the file

2. Sorted and sort

Sorted (iterable, Cmp=none, Key=none, Reverse=false)

  

3. Define the __init__ method of the person class to accept any keyword arguments in addition to the name, gender, and birth, and assign them all as attributes to the instance.

classPerson (object):def __init__(self,name,gender,birth,**kw): Self.name=name Self.gender=Gender Self.birth=Birth forKey,valueinchKw.items (): setattr (self,key,value) xiaoming= Person ('Xiao Ming','Male','1990-1-1', job='Student')PrintXiaoming.namePrintXiaoming.job

34 Please add a Class property count for the person class, and the Count property will add 1 for each instance, so that you can count the instances of how many of the person you have created altogether.

classPerson (object): Count=0def __init__(self,name): Self.name=name Person.count+ = 1P1= Person ('Bob')PrintPERSON.COUNTP2= Person ('Alice')PrintPERSON.COUNTP3= Person ('Tim')PrintPerson.count

5. Private variables of a class cannot be obtained directly, but can be obtained by means of a method instance or class-Private method

#get through the method of the instanceclassPerson (object):__count=0def __init__(self,name): Self.name=name person.__count+ = 1defget_count (self):returnPerson.__countP1= Person ('Alice') P2= Person ('Tom')PrintP1.get_count ()#= 2#Get By class private methodclassPerson (object):__count=0def __init__(self,name): Self.name=name person.__count+ = 1@classmethoddefget_count (self):returnSelf.__countP1= Person ('Alice') P2= Person ('Tom')PrintPerson.get_count ()#= 2

6. Inheritance and composition of classes

The definition of each class requires inheritance, and if not, it inherits from Object

6.1 Combination: Has relationship

6.2 Inheritance: Is relationship

Example:

class Person (object):     def __init__ (self, Name, gender):         = name        = genderclass  Teacher (person):    def__init_ _(self, name, gender, course):        Super (teacher,self).  __init__ (Name,gender) # or person.__init__ (self,name,gender)        Self.course = Course

7. polymorphic in Python

Class has an inheritance relationship, and the subclass type can be transformed upward as a parent class type, if we derive student and teacher from person, and both write a WhoAmI () method:

classPerson (object):def __init__(self, Name, gender): Self.name=name Self.gender=GenderdefWhoAmI (self):return 'I am A person, my name is%s'%Self.nameclassStudent (person):def __init__(self, name, gender, score): Super (Student, self).__init__(name, gender) Self.score=scoredefWhoAmI (self):return 'I am a Student, my name is%s'%Self.nameclassTeacher (person):def __init__(self, name, gender, course): Super (Teacher, self).__init__(name, gender) Self.course=CoursedefWhoAmI (self):return 'I am a Teacher, my name is%s'% Self.name

In a function, if we receive a variable x, the result can be printed correctly whether the X is a person, a student, or a Teacher:

defwho_am_i (x):PrintX.whoami () p= Person ('Tim','Male') s= Student ('Bob','Male', 88) T= Teacher ('Alice','Female','中文版') Who_am_i (p) who_am_i (s) who_am_i (t) Run Result: I am a person, my name isTimI am a Student, my name isBobi am a Teacher, my name isAlice

This behavior is known as polymorphism. In other words, the method invocation will work on the actual type of x. S is the student type, it actually has its own WhoAmI () method and the WhoAmI method inherited from person, but calling S.whoami () always finds its own definition, and if not defined, looks up the inheritance chain until it is found in a parent class.

Because Python is a dynamic language, the parameter x passed to the function who_am_i (x) is not necessarily a subtype of person or person. An instance of any data type can, as long as it has a WhoAmI () method:

class Book (object):     def WhoAmI (self):         return ' I am a book '

This is one of the biggest differences between dynamic and static languages, such as Java. A dynamic language invokes an instance method, does not check the type, and can be called as long as the method exists and the parameter is correct.

Task

Python provides an open () function that opens a disk file and returns a file object. The file object has a read () method to read the contents of the files:

For example, read the contents from a file and parse it into JSON results:

Import= open ('/path/to/file.json'r')  Print json.load (f)

Due to the dynamic nature of Python, json.load () does not necessarily read content from a file object. Any object, as long as the read () method is called a File-like object, can be passed to Json.load ().

Try writing a File-like object that wraps a string R ' [' Tim ', ' Bob ', ' Alice '] ' into a File-like object and parsed by Json.load ().

For
Import JSON class Students (object):     def Read (self):         return ' ["Tim", "Bob", "Alice"] '  = Students ()print json.load (s)

8. Special methods for Python classes

It should be stated that for simple numbers you can use the built-in CMP () function for sorted ()

But if it's not just numbers or not simple letters, we need to define our own __cmp__ ()

Define the __cmp__ () function, you can use CMP () to prioritize, CMP () is ascending,-cmp () is descending

Example

classStudent (object):def __init__(self, Name, score): Self.name=name Self.score=scoredef __str__(self):return '(%s:%s)'%(Self.name, Self.score)__repr__=__str__    def __cmp__(self, s):ifSelf.score = =S.score:returnCMP (self.name,s.name)return-CMP (self.score,s.score) L= [Student ('Tim', Student), ('Bob', Student), ('Alice', 99)]PrintSorted (L)#results returned: [(alice:99), (tim:99), (bob:88)]

Python scattered functions

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.