The third level of object-oriented, network programming practice

Source: Internet
Author: User

1. Object-oriented three major features, what is the use of each, to say your understanding.
Inheritance: Resolving code reuse issues
Polymorphism: The ability to use objects directly without regard to the object type
Encapsulation: explicit distinction between inside and outside, control of external operation behavior of hidden attributes, isolation complexity
2. What is the difference between a class's properties and an object's properties?
Properties of the class: Data properties and Function properties, data properties are common to all objects, and function properties are used by bindings to objects
Object properties: Object is an instantiation of a class
3. What are the differences and application scenarios for process programming and object-oriented programming?
Process-oriented: complex problem flow, simplified application scenario: No need to expand, monitoring scripts, automatic deployment scripts, software decompression installation
Object-oriented: The combination of feature and skill everything is Object application scenario: User needs change frequently, Internet application, game, Enterprise internal application
4. How classes and objects are stored in memory.
Properties of classes and objects: saved as a dictionary.
5. What is a method bound to an object, a method bound to a class, a function unbound, how to define it, how to call it, and for whom? What are the characteristics?
Methods bound to an object: it should be called by the object, Def tell_info (self): ... Obj.tell_info ()
Methods bound to a class: it should be called by the class, @classmethod def from_conf (CLS): ... class.from_conf ()
Unbound method: Not tied to class or object, anyone can call, @staticmethod def create_id (): ... obj.create_if ()/class.create_id ()
6. Use instances to get, set, delete data, which will trigger what private method of the class
1 # class A (object): 2 #     def __setitem__ (self, Key, value): 3 #         Self.__dict__[key] = value 4 # 5 #     def __getit Em__ (self, Item): 6 #         # return Self.__dict__[item] 7 #         return Self.__dict__.get (item) 8 # 9 #     def __delitem__ (  Self, Key): Ten #         del self.__dict__[key]11 #12 # a = A () # a["key"] = "val" # print (a.__dict__) # # a = a["key"]16 # # print (a) # del a["key"]18 # print (a.__dict__)
The difference between classic and modern classes in 7.python
Classic class: Py2 class that does not inherit object, and its subclasses are called classic---depth first
New class: Py3 inherits the class of object, and its subclasses are called new class--and breadth first
8. As an example, optimize the following code in an object-oriented manner
1 # 1, in the absence of the concept of learning class, the data and function are separated 2 # def exc1 (Host,port,db,charset): 3 #     Conn=connect (Host,port,db,charset) 4 #     Conn.execute (SQL) 5 #     return XXX 6 # def exc2 (host,port,db,charset,proc_name) 7 #     Conn=connect (host,port,db, CharSet) 8 #     Conn.call_proc (SQL) 9 #     return xxx10 # # Every call needs to pass in a bunch of arguments again and again # exc1 (' 127.0.0.1 ', 3306, ' db1 ', ' UTF8 ', ' SELECT * from TB1; ') # exc2 (' 127.0.0.1 ', 3306, ' db1 ', ' UTF8 ', ' name of Stored procedure ') # class Exec:15 #     def __init__ (self,proc_name):         Self.host= ' 127.0.0.1 ' #         self.port=330618 #         self.db= ' db1 ' #         self.charset= ' Utf-8         ' Self.proc_name=proc_name21 #22 # ex=exec (' Store name ') # ex2=exec (' Store Name 2 ') # print (ex.__dict__) # print (ex2.__dict__)
9. Example 1, the following code is present, what will be output:
1 class people (object): 2     __name = "Luffy" 3     __age = 4  5  6 p1 = people () 7 # Print (P1.__name, p1.__age) 8 "9 Attributeerror: ' People ' object has no attribute ' __name ', ' One # print (people.__dict__) # print (p1._people__ Name,p1._people__age) "__module__": ' __main__ ', ' _people__name ': ' Luffy ', ' _people__age ': ' __dict__ ': < Attribute ' __dict__ ' of ' people ' objects>, ' __weakref__ ': <attribute ' __weakref__ ' of ' people ' objects>, ' __doc_ _ ': none}15 luffy 1816 '
1 class people (object): 2  3    def __init__ (self,name): 4        print ("__init__") 5  6    def __new__ (CLS, * args, **kwargs): 7        print ("__new__") 8        Print (Args,kwargs) 9        return object.__new__ (CLS) Ten # People (' Alice ') "__new__14 __init__15"
11. Please explain briefly the Staticmethod (static method) and Classmethod (class method) in Python, and supplement the code separately to perform the following methods.
Static methods: Unbound methods, classes and objects are callable
Class method: A method that is bound to a class, called by a class
1 class A (object): 2     def __init__ (self,name): 3         self.name=name 4  5     def foo (self, x): 6         print (" Executing foo (%s,%s) "% (self,x)) 7  8     @classmethod 9     def class_foo (CLS, x):         Print (" Executing class _foo (%s,%s) "% (cls,x))     @staticmethod13     def static_foo (x):         print (" Executing Static_foo (%s) "% ( x) # a = A (' Alice ') # A.foo (' Alice ') # A.class_foo (' Alice ') # A.static_foo (' Alice ') # A.static_foo (' Alice ') 2 1 "Executing foo (<__main__. A object at 0x000002a5fed12ac8> Alice) executing Class_foo (<class ' __main__. A ', Alice ') executing Static_foo (Alice) executing Static_foo (Alice) 26 "
12. Execute the following code to explain the cause of the error and fix the error.
1 class Dog (object): 2  3    def __init__ (self,name): 4        self.name = Name 5  6    @property 7    def Eat ( Self): 8        Print ("%s is eating"%self.name) 9 d = Dog ("Chenronghua") # d.eat () # D.eat
13. What will be the output of this code? Please explain.
1 class Parent (object): 2    x = 1 3  4 class Child1 (parent): 5    Pass 6  7 class Child2 (parent): 8    Pass 9 # Print (Parent.x, child1.x, child2.x) # child1.x = 212 # print (parent.x, child1.x, child2.x) # parent.x = 314 #  Print (Parent.x, child1.x, child2.x) 15 16 # 1 1 1 inherit from the Class property X of the parent class, so all the same, point to the same piece of memory address 17 # 1 2 1 Change child1,child1 x points to the new memory address 18 # 3 2 3 Change parent,parent x points to a new memory address
14. The order of execution of multiple inheritance, please answer what are the following output results? and explained.
Super () represents the next in the MRO () List of subclasses.
Print (G.MRO ())
[<class ' __main__. G ';, <class ' __main__. D ';, <class ' __main__. A ';, <class ' __main__. B ';, <class ' object ';]
Print (F.MRO ())
[<class ' __main__. F ';, <class ' __main__. C ';, <class ' __main__. B ';, <class ' __main__. D ';, <class ' __main__. A ';, <class ' object ';]
 1 class A (object): 2 def __init__ (self): 3 print (' A ') 4 super (A, self). __init__ () 5 6 class B (object): 7 def __init__ (self): 8 print (' B ') 9 super (b, self). __init__ ()-Class C (A): def __init__ (self): 1        3 print (' C ') + super (C, self). __init__ () class D (A): + def __init__ (self): print (' D ') 19 Super (D, self). __init__ () class E (B, C): + def __init__ (self): + print (' E ') for super (E, self). __i NIT__ () class F (C, B, D): Def __init__ (self): + print (' F '), super (F, self). __init__ () G (D, B): Def __init__ (self): print (' G ') for super (g, self). __init__ () # if __name__ = = ' __main__ ': Panax Notoginseng # g = g () max # f = f () Max # Print (G.mro ()) Max # Print (F.mro ()) # G43 # D44 # A45 # B46 #47 # F48 # C49 # B50 # D51 # A52 # [<class ' __main__. G ';, <class ' __main__. D ';, <class ' __main__. A ';, <class ' __main__. B ';, <class ' ObjeCT ' >]53 # [<class ' __main__. F ';, <class ' __main__. C ';, <class ' __main__. B ';, <class ' __main__. D ';, <class ' __main__. A ';, <class ' object ';]
15. Write a code that conforms to the polymorphic characteristics.
1 class Animal:2     def __init__ (self, Name): 3         self.name = name 4  5  6 class people (Animal): 7     def talk ( Self): 8         print ('%s are talking '% Self.name) 9 class Dog (Animal):     def Talk (self):         print ('%s is talkin G '% self.name) + def func (animal):     animal.talk () # p=people (' Alice ') # D=dog (' Wang ') # func (P) 22 # Func (d) + "Alice is Talking25 Wang is talking26"
16. Many students have learned the object-oriented grammar, but still can not write the object-oriented program, why is it? The reason is because you haven't mastered an object-oriented design tool,
Domain modeling, explain what domain modeling is and how to design object-oriented programs through it?
http://www.cnblogs.com/alex3714/articles/5188179.html This blog is the most detailed after
    The domain model, as the name implies, is a modeling of the areas involved in the requirements, and the more popular is the business model.    definition:        requirements to object-oriented bridge    functions:        1. Explore key Business Domain Concepts        2. Establish the relationship between business domain Concepts     : A Zi Jing method for the        modeling of noun domain from use cases    : finding nouns, Add attributes, links.        Reference: Http://www.cnblogs.com/linhaifeng/articles/6182264.html#_label15              
17. Please write a small game, people dog station, 2 characters, people and dogs, after the game began, generate 2 people, 3 dogs, melee, people are bitten by the dog will Drop blood, the dog was beaten also lost blood,
Dogs and people have different abilities. Note that the class is designed in the same way as topic 14, Domain modeling.
1 class Animal:2     def __init__ (self, name,life_value,aggressivity): 3         self.name = name 4         self.life_value = Li Fe_value 5         self.aggressivity = aggressivity 6  7     def attack (Self,enemy): 8         Enemy.life_value-= Self.aggressivity 9 class people (Animal):     camp= ' home '     def attack (Self,enemy): +         Super (). Attack (enemy)         print (' from People ') (Animal):     camp= ' wo '     def attack (Self,enemy):         Super (). Attack (enemy)         print (' from dog ') p1=people (' Alice ', 80,30) p1=people (' Alex ', 80,30) D1=dog (' W1 ', 90,50) d2=dog (' W2 ', 90,50) d3=dog (' W3 ', 90,50) # print (p1.life_value) # D1.attack (p1) # print (P1.life_ Value) D1.life_value # print () # p1.attack (D1) # Print (D1.life_value)
18. Write a program that controls the capitalization of the data properties of a custom class in a meta-class.
19. Write a program that controls a custom class in a meta-class without the Init method.
1 class Mymeta (type): 2     def __new__ (cls,class_name,class_bases,class_dic): 3         update_dic = {} 4 for         I in class _dic:5             if not callable (Class_dic[i]) and not I.startswith (' __ '): 6                 Update_dic[i.upper ()]=class_dic[i] 7             Else:8                 Update_dic[i]=class_dic[i] 9         return type.__new__ (cls,class_name,class_bases,update_dic)     def __call__ (self, *args, **kwargs): All         obj=object.__new__ (self)         if args:14             raise TypeError (' must be Keyword argument ') for the         i in kwargs:16             obj.__dict__[i]=kwargs[i]17         return obj18 class Chinese ( Metaclass=mymeta):     country= ' China '     tag= ' Legend of the Dragon ' on     def talk (self):         print ( '%s is talking '%self.name) # print (chinese.__dict__) # Ch=chinese (name= ' Alice ', age=18) # ch.talk () # Print (ch. __DICT__)
20. Write a program, write a student class, ask for a counter attribute, and count how many students are instantiated in total.
1 class student:2     __count = 0 3     def __init__ (self, Name, age): 4         self.name = Name 5         self.age = age 6         Student.__count + = 1 7  8     @property 9     def talk ("Self"):         print ('%s is talking '% self.name)     STATICMETHOD13     def tell_count ():         print (' Total instantiation of%s people '% student.__count) # S1 = Student (' Alice ', ') # s 2 = Student (' Alex ', ') # s3 = Student (' Egon ', ") # Student.tell_count () # S1.tell_count () # s1.talk22 # S2.talk
21. Write the program, a inherits B, both classes implement the Handle method, and the handle method of B is called in the handle method in a
1 class B:2     def handle (self): 3         print ("from B handle") 4  5 class A (b): 6     def handle (self): 7         Super (). Handle () 8         # Print (' from A handle ') 9 # a=a () # A.handle ()
22. The program is written with three requirements as follows:
1. Customize the user information data structure, write to the file, then read the content, use the JSON module for data serialization and deserialization
e.g
{
"Egon": {"password": "123", ' status ': False, ' timeout ': 0},
"Alex": {"password": "456", ' status ': False, ' timeout ': 0},
}
2. Define the user class, define the method db, for example execute obj.db can get the user data structure
3. Implement login, Exit method in this class, log on successfully change status to True, exit change state to False (exit to determine if logged in).
Password input error three times will set the lockout time (logon is not allowed for the next logon if it is more than 10 seconds compared to the current time)
 1 Import JSON 2 import time 3 class User:4 def __init__ (self, Name, password): 5 Self.name = name 6          Self.password = password 7 self.status = False 8 self.timeout = 0 9 @property11 def db (self): 12 With open (self.name+ '. txt ', ' r ', encoding= ' Utf-8 ') as f:13 data = Json.load (f) Return data1 5 def Save (self): obj={}18 obj[self.name]={' password ': self.password, ' status ': Self.status, ' timeout     ': self.timeout}19 with open (self.name+ '. txt ', ' w ', encoding= ' Utf-8 ') as F:20 json.dump (obj,f) 21 22             def login (self): all with open (self.name+ '. txt ', ' r+ ', encoding= ' Utf-8 ') as f:24 data = Json.load (f) 25                 Count = 026 while count < 3:27 password = input (' Password>>: '). Strip () 28 If password! = data[self.name][' password ']:29 count + continu E31 Else: If data[self.name][' timeout ']! = 0:33 if Time.time ()-data[self.name][' Ti Meout '] > 10:34 print (' No login allowed! Timeout ') break36 else:37 data[self.name][' st                             ATUs '] = True38 f.seek (0) f.truncate () 40                     Json.dump (data, f) print ('----welcome----') Break43                         else:44 data[self.name][' status ' = True45 f.seek (0) 46 F.truncate () json.dump (data, f), print ('----welcome                 ----') break50 wuyi else:52 data[self.name][' timeout ']=time.time () 53 F.seek (0) f.truncate () Json.dump (dATA,F) (self): (self.name+ '. txt ', ' r+ ', encoding= ' Utf-8 ') as f:60 data                 = Json.load (f) If data[self.name][' status '] = = true:62 data[self.name][' status '] = False63                 F.seek (0) f.truncate () json.dump (data, F) else:67 Print (' You are out of state! * Alex=user (' Alex ', ' 123 ') # Egon=user (' Egon ', ' 456 ') # # Alex.save () # # Egon.save () # # # (ALEX.DB) # 7 5 # # print (egon.db) # # # Alex.login () # alex.quit () # # egon.quit () # Print (alex.db) # print (egon.db) bayi * * * Ale X.login () Egon.login # ()
‘‘‘
23. Write a teacher's role in object-oriented form, and achieve the following functions, get a list of teachers, create teachers, delete teachers,
After a successful creation, it is saved to the file via pickle serialization and can be read to the created teacher the next time the program is restarted, such as the program directory structure as follows.
‘‘‘
‘‘‘
.
|--bin/
| |--main.py program to run the main program (menu selection, etc.)
|--config/
| |--settings.py Program configuration (for example: Configuration store to create path correlation for teachers etc.)
|--DB data storage (persistent, so that the relevant data corresponds to the reservation each time the program is restarted)
| |--teachers/Store all teachers ' files
| |-- ... ...
|--src/Program Body Module Storage
| |--__init__.py
| |--teacher.py Example: Files that implement teacher-related functions
| |--group.py Example: Files that implement class-related functions
|--manage.py Program startup file
|--README.MD Program Documentation
‘‘‘
‘‘‘
24. According to 23 questions, and then write a class category, to achieve the following functions, create classes, delete classes, get class list, after the creation of a successful through pickle serialization saved to the file,
And can read to the created class the next time the program is restarted.
25. Based on the 23 questions, write a course class, achieve the following functions, create a course (create a request as above), delete a course, get a list of courses
26. According to the 23 questions, write school classes, achieve the following functions, create schools, delete schools, get a list of schools
27. Through the 23 questions, whether they have the same function, can be carried out in the way of inheritance some optimization

Pseudo code
Class Behavior (object):

def fetch (self, keyword):
Querying the corresponding data list with the keyword parameter

Class School (Behavior):

Pass

Class Teacher (Behavior):

Pass

s = School ()
t = Teacher ()

S.fetch ("school")
T.fetch ("Teacher")
‘‘‘
#---------See homework----------

The third level of object-oriented, network programming practice

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.