Python Foundation article-day7

Source: Internet
Author: User

This program-object oriented
Class 1 Introduction
1.1 Object-oriented OO features
Characteristics of Class 1.2
1.3 Creating and invoking
1.3.1 Basic Structure
1.3.2 Structure Description
1.3.3 provides read-only access to external interfaces
1.3.4 destructor method
2 inheritance
2.1 Inheritance Introduction
2.2 Transverse relationship (combination) vs vertical relationship (inheritance)
2.3 Built-in functions
2.3.1 Issubclass
2.3.2 Isinstance
2.3.3 Hassttr

Class 1 Introduction
1.1 Object-oriented OO features
Oo=object oriented
1. Encapsulation---information hiding technology
2. Inheritance---The mechanism by which subclasses automatically share data and methods between parent classes
3. Polymorphic---Different objects respond differently to the same method (different classes can have the same function name, and the response is based on the definition in the function)

Characteristics of Class 1.2
Packaging:
1, to prevent the data is arbitrarily modified; 2, so that the external program does not need to pay attention to the internal structure of the object, only through the interface provided by this object directly access can be;
Inherited:
The way the parent class-subclass is implemented in the most concise way, with different roles

1.3 Creating and invoking
1.3.1 Basic Structure
Class Creation object, which is called an instance of the class (instance object)
Class object (class, capital letter start) = attribute (variable) + method (function)
Class Tirle: #python中类以大写字母开头

Class Dog (object):
Nation = ' China ' #公有属性
def __init__ (Self,name,food): #构造函数, construction method = = Initialization function
Self.name = Name #成员属性
# Self.food = Food
Self.__heart = ' Namal ' #私有属性

def Wark (self): #类的方法
Print ('%s is dog '% self.name)
Def eat (Self,food):
Print ("%s is eating%s"% (Self.name,food))

D = Dog (' sss ', ' Dutou ') #实例化后产生的对象称为实例
D.wark ()
D.eat (' Baozi ')

1.3.2 Structure Description
Class-->> instantiation of-->> instances
Self is the object that invokes the current method
__init__ #构造方法
The return value is none, forcing the addition of the return value will give an error typeerror:__init__ () should return None
Self.name = Name #属性--the member property can be called outside, and an internal method can also invoke
Self.__name = name #私有属性 (externally invisible, internal methods can be called)
__private_attr_name = Value private Property
def sayhi () #方法
++++++++++++++++++++++++++
__init__ (self) Method: Construction method
The return value is none, forcing the addition of the return value will give an error typeerror:__init__ () should return None
>>> Class Ball:
def __init__ (self,name):
Self.name = Name
def kick (self):
Print (' I am%s, who kick me '% self.name)
>>> a = Ball (' a ')
>>> A.kick ()
I am A, who kick me
>>> a = Ball () #----->> must add parameter, otherwise error
Traceback (most recent):
File "<pyshell#29>", line 1, in <module>
A = Ball ()
TypeError: __init__ () Missing 1 required positional argument: ' Name '
Add default parameters:
>>> Class Ball:
def __init__ (self,name= ' null '):
Self.name = Name
def kick (self):
Print (' I am%s, who kick me '% self.name)
>>> a = Ball (' a ')
>>> A.kick ()
I am A, who kick me
>>> a = Ball ()
>>> A.kick ()
I am NULL, who kick me
Not adding default parameters will cause an error:
++++++++++++++++++++++++++


1.3.3 provides read-only access to external interfaces
def get_heart (self): #比较安全
Return Self.__heart
To force access to a private property:
R1._role__heart

Public properties: Properties that are accessible to all instantiated objects are public properties (defined directly in the class)
role.nation = ' US ' Change public properties
+++++++++++++++++++++++++++++++++
Private variables or functions: Defining a private variable or function in Python requires only the "__" two underscores in front of the variable or functional name
>>> class Person ():
__name = "a"
def getname (self):
Return Self.__name
>>> p = person ()
>>> P.__name
Traceback (most recent):
File "<pyshell#52>", line 1, in <module>
P.__name
Attributeerror: ' Person ' object with no attribute ' __name '
>>> P.getname ()
A
Pseudo-Private: Change the variable or function to the form "_ Class name __ variable name"
>>> P._person__name
A
+++++++++++++++++++++++++++++++++


1.3.4 destructor method
To delete an instantiated instance
def __del__ (self):
Print ("Del--run")


2 inheritance
2.1 Inheritance Introduction
There are 2 main implementations of the concept of inheritance: implementation inheritance, interface inheritance.
Implementation inheritance refers to the ability to use the properties and methods of a base class without additional coding;
Interface inheritance refers to the ability to use only the names of properties and methods, but subclasses must provide the implementation (subclass refactoring method);

Multiple inheritance--the difference between the order of inheritance (PY2, py3 all use breadth Query method to inherit)
New class, query using breadth query, all classes of the same class to complete the query before continuing to find in the previous layer of class
The classic class, the query uses the deep query, all the classes in depth are all queried before continuing to find in the other layers of the same layer

Class Subclass (base class, parent class, Super Class)
Class Derivedclassname (Baseclassname):
......
>>> Class Parent:
def hello (self):
Print (' Old JAKSJD parent ')
>>> class Child (parent):
Pass
>>> p = parent ()
>>> P.hello ()
Old JAKSJD Parent
>>> C = Child ()
>>> C.hello ()
Old JAKSJD Paren
Note: If a method or property with the same name as the parent class is defined in the child class, call its own property or method when called.
>>> Class Parent:
def hello (self):
Print (' Old JAKSJD parent ')
>>> class Child (parent):
def hello (self):
Print (' New JAKSJD child ')
>>> p = parent ()
>>> P.hello ()
Old JAKSJD Parent
>>> C = Child ()
>>> C.hello ()
New JAKSJD Child

Note: Classic class vs New Class #建议使用新式类
class Person (object): #new style
Super
Class Person: #classical style
parentclass.__init__
#SchoolMember. __init__ (self,name,age,sex) #经典类继承写法
Super (Teacher,self) __init__ (name,age,sex) #新式类继承写法


2.2 Transverse relationship (combination) vs vertical relationship (inheritance)
Class Tutle:
def __init__ (self,x):
Self.num = X

Class Fish:
def __init__ (self,x):
Self.num = X
Class Pool:
def __init__ (self,x,y):
Self.tutle = Tutle (x)
Self.fish = Fish (y)
def print_num (self):
Print (' The Totel of Tutle is%d in the pool,the Totel of fish are%d in the pool! '% (self.tutle.num,self.fish.num))
>>> pool = Pool (1,10)
>>> Pool.print_num ()
The Totel of Tutle is 1 in the pool,the Totel of fish is ten in the pool!

Mix_in
Binding:
Python's strict approach requires an instance to be called, and this restriction is Python binding.

2.3 Built-in functions
All classes are collectively referred to as: Object
2.3.1 Issubclass
Issubclass (class,classinfo) checks if class is a subclass of ClassInfo, yes returns true
1. A class is considered to be a subclass of itself
2. ClassInfo can be a tuple of class objects, as long as the class is a subclass of any of these candidate classes, and returns True
>>> Class A:
Pass
>>> Class B (a):
Pas
>>> Class C:
Pass
>>> Issubclass (A, B)
False
>>> Issubclass (B,a)
True
>>> Issubclass (A,a)
True
>>> Issubclass (c,b)
False
>>> Issubclass (A,object)
True

2.3.2 Isinstance
Isinstance (Object,classinfo) checks whether an instance object objects belong to a class ClassInfo,
1, if the first parameter is not an object, it will always return false
2. If the second parameter is not a class or a tuple consisting of a class object, the TypeError exception is thrown
>>> B1 = B ()
>>> isinstance (b1,b)
True
>>> isinstance (B1,a)
True
>>> Isinstance (B1, (A,B,C))
True

2.3.3 Hassttr
attr = attribute: Property
Hassttr (Object,name) checks whether an object has a specified property
Name represents a property name, which needs to be enclosed in single quotation marks in the format: ' Name '
>>> class C:
def __init__ (self,x=0):
Self.x=x
>>>
>>> C1 = C ()
>>> hasattr (C1, ' X ')
True
>>> hasattr (c1, ' Y ')
False
>>> hasattr (c1,x)
Traceback (most recent):
File "<pyshell#26>", line 1, in <module>
Hasattr (c1,x)
Nameerror:name ' x ' is not defined
GetAttr (Object,name[,default]) returns the value of the property specified in an object, if the specified property does not exist, when
Returns the default value when it is included, otherwise returns no attribute ' name '
>>> GetAttr (C1, ' X ')
0
>>> GetAttr (c1, ' Y ')
Traceback (most recent):
File "<pyshell#28>", line 1, in <module>
GetAttr (C1, ' Y ')
Attributeerror: ' C ' object has no attribute ' Y '
>>> GetAttr (c1, ' Y ', "the property you are accessing does not exist ...")
' The property you are accessing does not exist ... '
SetAttr (Object,name,value) Sets the value of the specified property in an object, creates a new property and assigns a value if the specified property does not exist
>>> setattr (c1, ' y ', ' fish ')
Delattr (object,name) deletes the specified property in an object and throws the specified property if it does not exist attributeerror
>>> GetAttr (c1, ' Y ')
' Fish '
>>> delattr (c1, ' Y ')
>>> delattr (c1, ' Y ')
Traceback (most recent):
File "<pyshell#36>", line 1, in <module>
Delattr (C1, ' Y ')
Attributeerror:y
Property (Fget=none,fset=none,fdel=none,doc=none) uses properties to control properties
>>> class C:
def __init__ (self,size=10):
Self.size=size
def getsize (self):
Return self.size
def setsize (Self,value):
Self.size=value
def delsize (self):
Del self.size
X=property (Getsize,setsize,delsize)
>>> C1=c ()
>>> c1.size
10
>>> c1.getsize ()
10
>>> c1.x=18
>>> c1.getsize ()
18

3 polymorphic

Polymorphism (POLYMORPHISN) is a technique that allows you to set a parent object to be equal to one or more of his child objects, after which the parent object can operate differently depending on the attributes of the child object currently assigned to it. To put it simply, it is a sentence: A pointer to the parent class type is allowed to be assigned a pointer to the child class type. So what is the role of polymorphism? We know that encapsulation can hide implementation details and make code modular; Inheritance can extend existing code modules (classes); they are all designed to-code reuse. And polymorphism is for another purpose--interface reuse! The role of polymorphism is to ensure that classes are called correctly when inheriting and deriving a property of an instance of any class in the family tree.

Python Foundation article-day7

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.