Object-Oriented (class) two
- Object-oriented is a programmatic approach that is implemented based on the use of classes and objects
- A class is a template that wraps multiple "functions" in a template (which can be used to encapsulate variables common in multiple functions into an object)
- Object, an instance created from a template (that is, an object) used to invoke a function that is wrapped in a class
- Object-oriented three major features: encapsulation, inheritance, and polymorphism
A multiple-inheritance instance of a class:
Class A: def f2 (self): print ("F2 from A") class B (a): def F1 (self): print (' F2 from B ') class C (a): C15/>def F1 (self): print (' F2 from C ') class D (b,c): PASSD = D () d.f2 ()
Members of the class
The members of a class can be divided into three main categories: fields, methods, and properties
First, the field
Fields include: normal fields and static fields, they differ in definition and use, and the most essential difference is where the memory is stored in different places,
- Normal field belongs to object
- Static fields belong to class
Class Province: # static field country = ' China ' def __init__ (self, name): # normal field Self.name = name# Direct access to normal field obj = Province (' Hebei province ') print (obj.name) # Direct access to static fields Province.country
As can be seen from the code above, "Ordinary fields need to access the" static field through the class access, in the use can be seen in the normal field and static field attribution is different. Its content is stored in a similar way as:
by but:
- Static field saves only one copy in memory
- Normal fields save one copy of each object
Scenario: When you create an object from a class, you use a static field if each object has the same field
Second, the method
Methods include: Common methods, static methods, and class methods, three methods in memory belong to the class, the difference is that the calling method is different.
- Normal method: Called by the object ; at least one self parameter; When the normal method is executed, the object that invokes the method is automatically assigned the value to auto;
- Class method: Called by the class ; at least one cls parameter; When the class method is executed, the class that invokes the method is automatically copied to the CLS;
- Static methods: Called by the class , no default parameters;
Class Foo: def __init__ (self, name): self.name = name def ord_func (self): "" defines a normal method with at least one self argument " " # Print Self.name print (' normal method ') @classmethod def class_func (CLS):" " defines a class method with at least one CLS parameter "" " print (' class method ') @staticmethod def static_func ():" " defines a static method with no default parameter" "" print (' static method ') # Call the normal method F = Foo () f.ord_func () # Call the class method Foo.class_func () # Call the static method Foo.static_func ()
The same point: for all methods, it belongs to the class (non-object), so only one copy is saved in memory.
different points: The method callers are different, and the parameters that are passed in automatically when the method is called are different.
Third, attribute
If you already know the methods in the Python class, the properties are very simple, because the properties in Python are actually variants of the common method .
For attributes, the following three points of knowledge are available:
- Basic use of attributes
- Two ways to define a property
1, the basic use of attributes
# ############### definition ############## #class Foo: def func (self): Pass # defines a property @property def prop ( Self): pass# ############### call ############## #foo_obj = foo () foo_obj.func () Foo_obj.prop #调用属性
The definition and invocation of a property is a few points to note:
- When defining, add @property adorners on the basis of common methods;
- When defined, the property has only one self parameter
- When called, no parentheses are required
Method: Foo_obj.func ()
Property: Foo_obj.prop
Note: The attribute has the meaning that it can be used to create and access the exact same illusion of the field when accessing the property.
Property is a variant of the method, and if there are no attributes in Python, the method can completely replace its functionality.
2. Two ways to define attributes
There are two ways to define a property:
- Adorners: Applying adorners on methods
- Static fields are: Static fields that define values as property objects in a class
Adorner mode: Apply @property adorner to ordinary method of class
We know that the classes in Python have classic and modern classes, and the properties of the new class are richer than those of the classic class. (If the class is following object, then the class is a modern Class)
Classic class with a @property adorner (as in the previous step)
# ############### Definition ############### class Goods: @property def Price: return "Xigang" # ####### ######## call ############## #obj = Goods () result = Obj.price # automatically executes @property decorated price method and gets the return value of the method
New class with three kinds of @property adorners
# ############### definition ############## #class Goods (object): @property def Price: print ' @property ' @price. Setter def price (self, value): print ' @price. Setter ' @price. deleter def-Price: print ' @price. Deleter ' # ############### calls ############## #obj = Goods () Obj.price # automatically executes @property decorated price method, and Gets the return value of the method Obj.price = 123 # automatically executes the @price. Setter-Modified price method, and assigns 123 to the method's parameter del obj.price # to automate @price. Delet Er-Modified Price method
Note: The properties in the classic class have only one access, which corresponds to the method that is @property decorated
The properties in the new class are accessed in three ways and correspond to three @property, @ method names. Setter, @ Method name. Method of Deleter Modification
Modifiers for class members
All members of the class have been described in more detail in the previous step, and there are two forms for each member of a class:
- Public members, accessible from anywhere
- Private members, only inside the class can the method
Private members and public members are defined differently : The first two characters are underlined when a private member is named. (except for special members, e.g. __init__, __call__, __dict__, etc.)
| 12345 |
class c: def __init__ ( self self .name = ' public field '      &NBSP, self = "private Field" |
Private members and public members have different access restrictions :
Static fields
- public static fields: classes are accessible, inside classes can be accessed, and in derived classes
- private static field: Only the class can be accessed internally;
Class C: name = "public static field" def func: print (C.name) class D (c): def Show (self): print (c.name) C.name # class Access obj = C () obj.func () # class inside can access Obj_son = D () obj_son.show () # derived classes can access
Class C: __name = "private static field" def func: print C.__nameclass D (C): def Show (self): print C._ _namec.__name # class access ==> error obj = C () obj.func () # class inside can access ==> correct Obj_son = D () obj_son.show () # ==> errors can be accessed in derived classes
Reflection Instances
Import Sysclass WebServer: def __init__ (self,host,port): self.host = host Self.port = Port def start ( Self): the print (' Server is starting ... ') def Stop (self): print (' Server is stopping ... ') def restart ( Self): self.stop () Self.start () def test_run (self,name): print (' Running ... ', name,self.host) if __ name__ = = ' __main__ ': server = WebServer (' localhost ', 333) server2 = WebServer (' localhost ', 333) if Hasattr (Server,sys.argv[1]): func = GetAttr (server,sys.argv[1]) func ()
Socket
Sockets are also commonly referred to as "sockets," which describe IP addresses and ports, and are a handle to a chain of communication, where applications usually make requests to the network through "sockets" or respond to network requests.
Sockets originate from UNIX, and one of the basic philosophies of unix/linux is "Everything is file", and the file is operated with "open" "Read and Write" "Off" mode. Socket is an implementation of this pattern, the socket is a special kind of file, some of the socket function is the operation of it (read/write Io, open, close)
The difference between a socket and file:
- The file module is "open", "Read and write" "Close" for a specified document
- The socket module is "open", "Read and write" "Off" for server-side and client sockets
Service side:
#!/usr/bin/Env python#-*-coding:utf-8-*-Import Socketip_port= ('127.0.0.1',9999) SK=Socket.socket () sk.bind (Ip_port) Sk.listen (5) whileTrue:print ('Server Waiting ...') conn,addr=sk.accept () client_data= Conn.recv (1024x768) print (client_data) Conn.sendall ('Don't answer, don't answer , don't answer') Conn.close ()
Client:
#!/usr/bin/env python#-*-coding:utf-8-*-import socketip_port = (' 127.0.0.1 ', 9999) SK = Socket.socket () sk.connect (ip_ Port) Sk.sendall (' request to occupy the earth ') server_reply = Sk.recv (1024x768) print server_replysk.close ()
Web Service Applications:
#!/usr/bin/env pythonimport socketdef handle_request (client): buf = Client.recv (1024x768) client.send ("http/1.1 ok\r\n\r\n ") client.send (" Hello, World ") def Main (): sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM) sock.bind ((' localhost ', 8080)) Sock.listen (5) while True: connection, address = Sock.accept () handle_request (connection) connection.close () if __name__ = = ' __main__ ': Main ()
Python Learning Note day7