Class (sixth day), python study notes, etc.

Source: Internet
Author: User

Class (sixth day), python study notes, etc.

 

Reference:

1, Kingdom blog: http://www.cnblogs.com/alex3714/articles/5188179.html

2, silver horn King blog: http://www.cnblogs.com/wupeiqi/articles/5017742.html

 

1. Reflection of _ import __:

We know that the import statement is used to import external modules. Of course, there is also from... import... yes, but in fact, the import function uses the builtin function _ import _ to work.
In some programs, we can call functions dynamically. If we know the module name (string), we can easily use dynamic calls.

_ Import _ (module_name [, globals [, locals [, fromlist]) # The optional parameters are globals (), locals (), and [] by default.
_ Import _ ('OS ')
_ Import _ ('OS', globals (), locals (), ['path', 'pip ']) # equivalent to from OS import path, pip

For example, import the module as a string

Mod = _ import _ ('sys ')
Print (mod. path)

For example, call a function in the module as a string.

Func = getattr (mod, 'path ')
Print (func)

For example, import a module from a package. The package name is main and the module name is mod.

Aa = _ import _ ('main. mod ')

Aa = _ import _ ('main', globals = {}, locals = {}, fromlist = ['mod'])

Aa = _ import _ ('main', globals (), locals (), ['mod'])

M = getattr (aa, 'mod ')
Print (m. first ('kevin '))

N = getattr (m, 'first ')
Print (type (n ))
N ('kevin ')

Note: different modules are loaded based on different URLs in the web Framework for different processing.

 

2. Classes and objects:

_ Init _ method to complete initialization. Constructor

Destroy the _ del _ method object, destructor

_ Call Method

All instance methods have a self parameter to pass the current instance, similar to this.
You can use _ class _ to access type members.

There are also some built-in special attributes:

_ Doc _ # type help information

_ Name _ # type name

_ Module _ # module of the type
_ Bases _ # base class inherited by the Type

_ Dict _ # type dictionary, which stores information about all types of members.

Example:

Class peason (object ):
'''This is peason class '''
# Static Fields
Aa = 'nihao'
Bb = ['A', 1, 'B', 2, 'C', 3]
Cc = {'A': 'hangai', 'B': 'gonghu '}

Def _ init _ (self, name, flag ):
Self. name = name # dynamic field
Self. _ flag = flag # private field


Def _ del _ (self ):
Print ('I will go ')

Def _ call _ (self, caa): # call Method
Print ('this is call method', caa)


Def _ priv (self): # private Method
Print ('hello, this is privacy method', self. _ flag)


Def first (self): # Dynamic Method
Print ('hello, this is dymamic method ', self. name)
Self. _ priv () # Call a private Method
Return self. _ flag # Call a private field

@ Staticmethod # static method
Def foo ():
Print ('this is static method ')

@ Property # attributes
Def bar (self ):
Print (self. name)
Self. _ priv ()
Return "this is property"

@ Property # Attribute (read-only)

Def flag (self ):
Return self. _ flag

@ Flag. setter # modify the private field value
Def flag (self, value ):
Self. _ flag = value

Print ('#################')
Print (peason. _ doc __, peason. _ name __, peason. _ module __, peason. _ bases __, peason. _ dict __)
Print ('#################')
Print (peason. aa, peason. bb, peason. cc) # obtain static Fields
Print ('#################')
Print (peason. foo () # obtain static methods
Print ('#################')
Pp = peason ('wang ', 'true') # class instantiation
Print (pp. name) # obtain dynamic fields through objects
Print ('#################')
Print (pp. first () # obtain dynamic methods through objects
Print ('#################')
Print (pp. bar) # Get attributes through objects
Print ('#################')
Print (pp. _ peason _ priv () # special call Method
Print ('#################')
Print (pp. flag)
Pp. flag = 'false' # modifying private field values through attributes
Print (pp. flag)

Pp ('A') # call method call

Note: static data can be accessed directly through classes, but dynamic data can only be accessed through calling objects;

Private fields and methods can be called through methods and properties;

For read-only or write-only fields, modification requires @ flag. setter and class peason (object ):

 

3. Inheritance:

In Python programming, classes can inherit attributes of the class, in the form of class name (parent class). subclasses can inherit all methods and attributes of the parent class, you can also overload the member functions and attributes of the parent class. Note that if the member functions of the Child class are overloaded with the same name, the member functions of the Child class are used.

Example:

Class SchoolMember (object ):
Members = 0 # the initial number of students is 0.
Def _ init _ (self, name, age ):
Self. name = name
Self. age = age

Def tell (self ):
Pass

Def enroll (self ):
'''Register '''
SchoolMember. members + = 1
Print ("\ 033 [32; 1 mnew member [% s] is enrolled, now there are [% s] members. \ 033 [0 m "% (self. name, SchoolMember. members ))

Def _ del _ (self ):
'''Destructor '''
Print ("\ 033 [31; 1 mmember [% s] is dead! \ 033 [0 m "% self. name)

Class Teacher (SchoolMember ):
Def _ init _ (self, name, age, course, salary ):
Super (Teacher, self). _ init _ (name, age)
Self. course = course
Self. salary = salary
Self. enroll ()


Def teaching (self ):
'''Lecture method '''
Print ("Teacher [% s] is teaching [% s] for class [% s]" % (self. name, self. course, 's12 '))

Def tell (self ):
'''Method of self-introduction '''
Msg = ''' Hi, my name is [% s], works for [% s] as a [% s] teacher! ''' % (Self. name, 'oldboys', self. course)
Print (msg)

Class Student (SchoolMember ):
Def _ init _ (self, name, age, grade, sid ):
Super (Student, self). _ init _ (name, age)
Self. grade = grade
Self. sid = sid
Self. enroll ()


Def tell (self ):
'''Method of self-introduction '''
Msg = ''' Hi, my name is [% s], I'm studying [% s] in [% s]! ''' % (Self. name, self. grade, 'oldboys ')
Print (msg)

If _ name _ = '_ main __':
T1 = Teacher ("Alex", 22, 'python', 20000)
T2 = Teacher ("TengLan", 29, 'linux, 3000)

S1 = Student ("Qinghua", 24, "Python S12", 1483)
S2 = Student ("SanJiang", 26, "Python S12", 1484)

T1.teaching ()
T2.teaching ()
T1.tell ()

New classes are based on objects. In Versions later than python3, classic classes will not be used, and the inheritance of new classes replaces the deep search of classic classes with breadth.

For example, class A, B, C, and D. B and C inherit from A, D inherit from B and C, that is, class D (B, C)

Inheritance Method:

The classical search order is B, A, and C. The first method is searched and ended.

The search sequence of the new category is B and C.

Example: classical writing

Class A (object ):
Def _ init _ (self ):
Print ('this is class ')
Def test (self ):
Print ('this is parent test ')

Class B ():
Def _ init _ (self ):
Print ('this is class B ')

Class C ():
Def _ init _ (self ):
Print ('this is class C ')
Def test (self ):
Print ('this is son C test ')

Class D (B, C ):
Def _ init _ (self ):
Print ('this is class D ')

R = D ()
R. test ()

The result of classic writing is:

This is class D
This is parent test

The new category is written as follows:

This is class D
This is son C test

 

4. abstract class + abstract method = interface (for Standardization)

Because python does not have abstract classes or interfaces, You need to implement the abc. py class library,

Abstract base classes (or ABCs) are the same features in Python. The abstract base class consists of the abc module and contains a metaclass called ABCMeta. This metaclass is specially processed by built-in isinstance () and issubclass ().

The procedure is as follows:

From abc import ABCMeta, abstractmethod
From _ pyio import _ metaclass __

Class headers (object ):
_ Metaclass _ = ABCMeta

Def _ init _ (self ):
Print ('this is abc class ')

@ Abstractmethod
Def fun (self ):
Pass

Class foo (headers ):
Def _ init _ (self ):
Print ('_ init __')

Def fun (self ):
Print ('foo. fun ')

F = foo ()
F. fun ()

Related Article

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.