Python Study notes Class (sixth day)

Source: Internet
Author: User

Reference Documentation:

1, King Kok Wang Blog: http://www.cnblogs.com/alex3714/articles/5188179.html

2, Silver corner King Blog: http://www.cnblogs.com/wupeiqi/articles/5017742.html

1, reflection of the __import__:

We know that the import statement is for importing external modules, and of course from...import ... Yes, but actually import actually works using the BUILTIN function __import__.
In some programs, we can dynamically call the function, if we know the name of the module (string), we can easily use dynamic invocation.

__import__ (module_name[, globals[, locals[, FromList]]) #可选参数默认为globals (), locals (), []
__import__ (' OS ')
__import__ (' OS ', Globals (), locals (), [' Path ', ' Pip ']) #等价于from OS import path, Pip

Example: Importing a module as a string

MoD = __import__ (' sys ')
Print (Mod.path)

Example: Calling a function in a module as a string

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

Example: Import a module from a package named Main, module named 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: The Web framework loads different modules according to different URLs and handles them differently.

2. Classes and objects:

The __init__ method completes the initialization. constructor function

__del__ method Object Destruction, destructor

__call__ Calling 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 properties:

__doc__ #类型帮助信息

__NAME__ # type Name

__MODULE__ # Type Module
__BASES__ # types inherit from base class

__DICT__ # Type Dictionary that stores all type member information.

Cases:

Class Peason (object):
' This is Peason class '
#静态字段
aa = ' Nihao '
bb = [' A ', 1, ' B ', 2, ' C ', 3]
CC = {' A ': ' Wangkai ', ' B ': ' Gonghui '}

def __init__ (Self,name,flag):
Self.name = Name #动态字段
Self.__flag = Flag #私有字段


def __del__ (self):
Print (' I'll go ')

def __call__ (SELF,CAA): #call方法
Print (' This was Call method ', CAA)


def __priv (self): #私有方法
Print (' Hello,this is Privacy method ', Self.__flag)


def first (self): #动态方法
Print (' Hello,this is Dymamic method ', Self.name)
Self.__priv () #调用私有方法
return Self.__flag #调用私有字段

@staticmethod #静态方法
def foo ():
Print (' This is static method ')

@property #属性
def bar (self):
Print (Self.name)
Self.__priv ()
Return "This was property"

@property #属性 (Read only)

def flag (self):
Return Self.__flag

@flag. Setter #修改私有字段值
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) #获取静态字段
Print (' ################# ')
Print (Peason.foo ()) #获取静态方法
Print (' ################# ')
pp = Peason (' Wang ', ' true ') #类实例化
Print (Pp.name) #通过对象获取动态字段
Print (' ################# ')
Print (Pp.first ()) #通过对象获取动态方法
Print (' ################# ')
Print (Pp.bar) #通过对象获取属性
Print (' ################# ')
Print (Pp._peason__priv ()) #特殊调用方式
Print (' ################# ')
Print (Pp.flag)
Pp.flag = ' false ' #通过属性修改私有字段值
Print (Pp.flag)

PP (' AA ') #call方法调用

Note: Static can be accessed directly through the class, while the dynamic can only be accessed by invoking the object's way;

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

Read-only or write-only fields, modifications require @flag.setter and class Peason (object): to implement

3. Inheritance:

In Python programming, a class can inherit a parent class name (the parent class), a subclass that inherits all the methods and properties of the parent class, or the member functions and properties of the parent class, and it is important to note that if the subclass member function overloads the parent class (that is, the name is the same), the subclass member function is used

Cases:

Class Schoolmember (object):
Members = 0 #初始学校人数为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;1mnew member [%s] is enrolled,now there be [%s] members.\033[0m"% (self.name,schoolmember.members))

def __del__ (self):
"' Destruction method '
Print ("\033[31;1mmember [%s] is dead!\033[0m"%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):
"The method of lecturing"
Print ("Teacher [%s] is teaching [%s] for class [%s]"% (self.name,self.course, ' S12 '))

def tell (self):
"Self-Introduction method"
msg = ' Hi, my name is [%s], works for [%s] as a [%s] teacher! '% (self.name, ' Oldboy ', 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):
"Self-Introduction method"
msg = ' Hi, my name is [%s], I ' m studying [%s] in [%s]! '% (Self.name, Self.grade, ' Oldboy ')
Print (msg)

if __name__ = = ' __main__ ':
T1 = Teacher ("Alex", page, ' Python ', 20000)
T2 = Teacher ("Tenglan", +, ' Linux ', 3000)

S1 = Student ("Qinghua", "Python S12", 1483)
S2 = Student ("Sanjiang", +, "Python S12", 1484)

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

The new class takes object as the base class, and after the Python3 version there is a classic class that will not be used, and the multi-class inheritance of the new class is to take the breadth instead of the classic class deep search mode.

examples, a, B, C, D four classes, where B and C inherit a,d and inherit B and C, that is, Class D (B,c)

Methods of Inheritance:

The search order for the classic class is B,a,c search to the end of the first method

The search order for the new class is b,c.

Example: Classic class notation

Class A (object):
def __init__ (self):
Print (' This is Class A ')
def test (self):
Print (' This is parent test ')

Class B (A):
def __init__ (self):
Print (' This is Class B ')

Class C (A):
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 the classic class is:

This is class D
This is the parent test

The result of the new class is:

This is class D
This is son C test

4. Abstract class + Abstract method = Interface (for specification)

Since Python does not have the concept of abstract classes and interfaces, it is abc.py this class library to implement this function.

The abstract base class (or ABCs) is one of the same features in Python. The abstract base class consists of an ABC module that contains a metaclass called Abcmeta. This metaclass is specially handled by the built-in isinstance () and Issubclass ()

The following are the specific methods:

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 ()

Python Study notes Class (sixth day)

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.