程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python basics -day10 (object oriented)

編輯:Python

1、 The concept of object orientation

The process of categorizing a class that has common attributes is called object-oriented .

2、 matters needing attention

class When defining a class , The first letter of a class name must be capitalized

3、 Object oriented case

 1 class Person(object):
2 def __init__(self,name,age): #name,age It can be understood as the attribute of a class ;init For initialization ; The functions defined in a class are called constructors / Constructors
3 self.name=name # Instance attributes
4 self.age=age
5 print("start")
6 def __del__(self): # Cleanup operations
7 print("end")
8 def show(self): #self For the class itself , Do not omit
9 print("name:{0},age:{1}".format(self.name,self.age))
10 obj=Person(name="wuya",age=18) # To call a variable in a class 、 Methods, functions, etc , First, you need to instantiate the class ;obj It's a class Person() Instantiated object , The process of class instantiation is also the process of class initialization . The instantiation process of a class is also the process of initializing a constructor ( It's called __init__ Methods )
11 obj.show()
12 #Person(name="wuya",age=18).show() # Call method with class name

The result of running the above code is :

4、 The execution order of the methods in the class : Initialization method -> Specific method -> Cleaning method

5、 Object oriented features

1) encapsulation

a. Instance attributes

b. Data attribute ( Variables in class )

2) Inherit

3) polymorphic

6、 Method :

a. Common method : Belong to the object , Also belong to class , Can only read and write ;

b. Characteristic method : Belong to the object , Only the read attribute is available , Methods cannot have formal arguments ;

c. Static methods : Belong to category , Can only be called with class name , Generally, data attributes are handled by static methods

7、 Encapsulate the starter instance

 1 class Animal(object):
2 def __init__(self,age):
3 self.age=age
4 def getAge(self):
5 return self.age
6 def setAge(self,age):
7 if age>10 and age<100:
8 self.age=age # It is allowed to modify the age
9 else:
10 print(" Age error ")
11 objAnimal=Animal(age=25) # Class instantiation
12 print(objAnimal.getAge()) # Output the call result of the method to get the age
13 objAnimal.setAge(age=11) # Call the method to modify the age
14 print(objAnimal.getAge()) # Output the call result of the method to get the age

8、 Advanced instances of encapsulation

 1 class Animal(object):
2 address=" The earth " # Data attribute
3 def __init__(self,age):
4 self.age=age # Instance attributes
5 # @staticmethod
6 def address(self): # Static methods , Data attributes are handled using static methods
7 return " The earth "
8 def show(self,name="*"): # Common method , read-write
9 print("it come from {0},and it's age is {1},and it's name is {2}".format(self.address(),self.age,name))
10 def func(self,**kwargs):
11 print(kwargs)
12 @property
13 def info(self): # Characteristic method , read-only ( Only output )
14 print("hello world")
15 @property
16 def getAge(self): # Characteristic method , read-only ( Only return to )
17 return self.age
18 objAnimal=Animal(age=30) # Class instantiation
19 objAnimal.show() # Calling normal methods
20 #objAnimal.show(name="monkey")
21 # Animal().show(name="monkey")
22 # Animal(age=10).address()
23 objAnimal.func(name="cch",age=18,city=" Xi'an ")
24 objAnimal.info # Feature method calls
25 print(Animal.address(""))
26 print(objAnimal.age)

 9、 Inherit

1) Concept

Parent class ( Base class ): Inherited class

Subclass ( Derived class ): Inherit other classes

2)Java and Python The difference between inheritance

Java It's a single inheritance ,Python It's multi inherited

3) Inherit from the parent class of :

a、 Variable ( Data attribute )

b、 Instance attributes

c、 Method

3) Method rewriting

When the methods of the parent class cannot meet the needs of the child class , The subclass overrides the methods of the parent class , Then the object after subclass instantiation calls this method , Priority is given to subclass methods .

 1 class Father(object):
2 address=" Xi'an "
3 def __init__(self,name,age):
4 self.name=name
5 self.age=age
6 def info(self):
7 print("this is a father's method")
8 class Son(Father):
9 def __init__(self,name,age,score):
10 Father.__init__(self,name,age) # The subclass inherits the instance property of the parent class
11 self.score=score
12 def show(self):
13 print("name is {0},and age is {1},and score is {1}".format(self.name,self.age,self.score))
14 def info(self): # The method of the parent class overrides
15 print("this is a son's method")
16 son=Son(name="wuya",age=18,score=99)
17 son.show()
18 print(son.address) # The subclass inherits the variables of the parent class ( Data attribute )
19 son.info() # no need print,info() There is print, Function and return value , The output function is null . Subclasses override methods of the parent class , Then the object after subclass instantiation calls this method , Priority is given to subclass methods .

The result of running the above code is :

 10、 Inheritance order

1) From top to bottom ( Prerequisite ):

a. Single inheritance

b. The subclass overrides the method of the parent class

2) From left to right ( Prerequisite ): Subclasses inherit from multiple classes ( Subclasses can inherit multiple parent classes , But the parent classes must be siblings .)

3) So in Python in , be based on MRO The parsing order rule of , You'll start looking for the base class from left to right , If you find the second one ⼀ Matching attribute classes , It will stop ⽌ lookup , without , Then keep looking , Until you find a match

To the end .MRO It's really just through ⼀ individual C3 Linear algorithm to achieve , Its core idea is :

Subclasses will be superior to parent class checking

Multiple parent classes are checked in turn according to their order in the list

If there are two legitimate choices for the next class , Only the first... Can be selected ( Linear search )

11、 Examples of inheritance order

 1 class Father(object):
2 def __init__(self,name,age):
3 self.name=name
4 self.age=age
5 def funM(self):
6 print("father")
7
8 class Mother(object):
9 def funM(self):
10 print("mother")
11
12 class Son(Father,Mother): # Subclass Son Inherited two parent classes
13 def __init__(self,name,age,score):
14 Father.__init__(self,name,age) # Subclass Son Inherited the parent class Father and Mother Instance properties for
15 self.score=score
16
17 son=Son(name="ccj",age=18,score=100)
18 son.funM()
19 print(Son.mro()) # Call... With a class name mro, View the execution order of the class

The execution result of the above code is :

12、 Subclass inherits multiple non sibling parent class error examples

 1 class Person(object):
2 pass
3
4 class Father(Person):
5 def __init__(self):
6 pass
7 def funM(self):
8 print("father")
9 class Mother(object):
10 def funM(self):
11 print("mother")
12
13 class Son(Person,Father): # The child class inherits multiple parent classes that are not of the same level , The code will report an error ,z Subclasses can inherit multiple parent classes , But the parent classes must be siblings .
14 def __init__(self,score): 15 Father.__init__(self) 16 self.score=score 17 son=Son(score=90) 18 son.funM() 19 print(Son.mro())

The running result of the above code is ;

 13、 Examples of inherited method call errors

 1 class Person(object):
2 pass
3
4 class Father(Person):
5 def __init__(self):
6 pass
7
8 class Mother(Person):
9 def funM(self):
10 print("mother")
11
12 class Son(Father): # There is no... In the parent class inherited by the subclass funM Method , The code will report an error
13 def __init__(self,score):
14 Father.__init__(self)
15 self.score=score
16
17 son=Son(score=99)
18 son.funM()

The running result of the above code is :

14、 Example of inherited method call error correction

 1 class Person(object):
2 def funM(self):
3 print("person")
4
5 class Father(Person):
6 def __init__(self):
7 pass
8
9 class Mother(Person):
10 def funM(self):
11 print("mother")
12
13 class Son(Father): # The parent class of the subclass inheritance method is Father
14 def __init__(self,score):
15 Father.__init__(self)
16 self.score=score
17
18 son=Son(score=99)
19 son.funM() # Subclasses call methods , First, look up... From the subclass , Then find the inherited parent class , If you don't find , Then find the parent class of the parent class .
20 print(Son.mro())

The result of the above method is :

15、 The question of inheritance history

python2 It's depth first ,python3 It's breadth first

 1 class A:
2 def show(self):
3 print('A')
4
5 class B(A):
6 pass
7
8 class C(A):
9 def show(self):
10 print('C')
11
12 class D(B,C):
13 pass
14
15 if __name__ == '__main__':
16 obj=D()
17 obj.show() #python2 The result of the execution is A,pyhton3 The result of running in is C

16、 polymorphic

Many advantages can be summarized as follows , Specific for :

Increased continuous flexibility

Added continuous additional extensions

 1 class Animal(object):
2 def talk(self):
3 print(" Animals can call ")
4
5 class Dog(object):
6 def talk(self):
7 print(" A dog barks ")
8
9 class Cat(object):
10 def talk(self):
11 print(" Cats bark, too ")
12
13 def func(animal):
14 animal.talk()
15 if __name__ == '__main__':
16 dog=Dog()
17 func(animal=dog)

The running result of the above code is :

python Basic knowledge of -day10( object-oriented ) More articles about

  1. Python Development 【 Second articles 】:Python Basic knowledge of

    Python Basic knowledge of One . First knowledge of basic data types type : int( integer ) stay 32 On the bit machine , The number of digits of an integer is 32 position , The value range is -2**31-2**31-1, namely -2147483648-2147483647 stay 64 position ...

  2. python Basic knowledge of ( One )

    python Basic knowledge of ( One ) One .python Introduction to development Python Was founded by Guido van Rossum.1989 During Christmas , In Amsterdam ,Guido In order to kill the boredom of Christmas , Determined to develop a new script ...

  3. python Summary of basic knowledge - Operation and Maintenance Notes

    Contact python It's been a while , The following for python The use of basic knowledge to do a complete comb :1) avoid ‘\n’ And so on : a) Using escape character ‘\’ b) Using the original characters ‘r’ print r'c:\now' ...

  4. Python Basic knowledge of (Basic knowledge)

    Python Basic knowledge of (Basic knowledge) 1. know Python& Basic environment construction 2.Python Basics ( On ) 3.Python Basics ( in ) 4.Python Basics ( Next ) 5.Python ...

  5. python Learning and understanding of basic knowledge

    Reference link :https://github.com/yanhualei/about_python/tree/master/python_learning/python_base   python Basic knowledge pen ...

  6. python Basic knowledge of ( Two )

    The following content , As python Supplement of basic knowledge , It mainly involves the creation and characteristics of basic data types , And new data types Bytes Introduction of type

  7. python Basic knowledge explanation ——@classmethod and @staticmethod The role of

    python Basic knowledge explanation ——@classmethod and @staticmethod The role of In a member function of a class , You can add @classmethod and @staticmethod Modifier , There is a certain difference between the two , Simple ...

  8. python There are five modules in crawler : The crawler starts the entry module ,URL The manager stores the crawler's URL And reptiles URL list ,html Downloader ,html Parser ,html Output device At the same time, we can master urllib2 Use 、bs4(BeautifulSoup) Page parser 、re Regular expressions 、urlparse、python Basic knowledge review (set Set operations ) And so on .

    This time python A hundred steps Encyclopedia of reptiles , There is a detailed analysis of the steps of the crawler , There are detailed comments on each step of the code , It can be grasped through this case python The characteristics of reptiles : 1. Crawler dispatch entry (crawler_main.py) # coding: ...

  9. python Crawlers and data visualization --python Basic knowledge of

    Abstract : Come into contact with by chance python voice , I think the grammar is simple . Powerful , Just a friend shared an online class <python Crawlers and data visualization >, So in work and leisure time to learn , And do the following course notes , The whole is roughly divided into 4 individual ...

  10. Python Basic knowledge of ( 5、 ... and )

    # -*- coding: utf-8 -*-# @Time : 2018-12-25 19:31# @Author : Three Jin aphrodisiac # @Email : [email protected]# @Fi ...

Random recommendation

  1. extjs Simple animation 2

    var store = Ext.create('Ext.data.Store', { storeId:'employeeStore', fields:['name', 'seniority', 'de ...

  2. Redis Four : An ordered collection of storage types

    Ordered sets seem to have a larger operation due to the addition of a called “ molecular ” Things that are In fact, it's like ordinary data , Just add a pure digital identifier to this data , By manipulating these identifiers, we can get the data we want ! Molecules can be plastic , It can also be double precision floating point type : = ...

  3. UVa 400 Unix Is

    The question : give n A string , Arrange in dictionary order , Then output according to the rules . === The purple book of learning , The meaning of the title is very clear , Find the number of columns and rows. At first, you can understand them Number of columns : That is to say (60-M)/(M+2)+1; That is to subtract... From the last column first , Suanpu ...

  4. Linux - Quick access to the directory

    cd Command technique Go directly to the user's home Catalog : cd ~ Go to the previous Directory : cd - Go to the next level of the current directory : cd .. Go to the upper two levels of the current directory : cd ../.. Other common methods utilize tab key , Automatically ...

  5. 【bzoj3218】a+b Problem Minimum cut + Chairman tree

    Data range :$n≤5000$,$a,l,r≤10^9$,$b,w,p≤2\times 10^5$. We consider a violent minimum cut approach : Let's start with $sum=\sum\limits_{i=1}^{n} b_i+w ...

  6. [ turn ] HBase abnormal :hbase-default.xml file seems to be for an old version of HBase

    [From] https://blog.yoodb.com/yoodb/article/detail/157 Use HBase Java Client Connect HBase Server creation Configuration Yes ...

  7. Luogu P2831 Angry birds

    Luogu P2831 Angry birds Original link Answer key First, a simple mathematical formula is presented . \(ax_1^2+bx_1=y_1\) \(ax_2^2+bx_2=y_2\) \(ax_1^2x_2+bx_1x_2=y_1x_2 ...

  8. xdebug Common configuration

    ; Appoint xdebug file zend_extension = "F:\tools\develop_tools\php\php_xdebug-2.2.2-5.4-vc9.dll" ;xd ...

  9. Beijing Uber Uber driver incentive policy (11 month 16 Japan ~11 month 22 Japan )

    User group : People Uber “ Guanyu group ”( Apply to 11 month 16 Japan -11 month 22 Japan ) Incentives : The express is just 2.5 times , Registered address :http://www.udache.com/ How to sign up Uber The driver ( National version of the latest and most detailed registration process )/ ...

  10. .NET C# Generate random colors , You can control the brightness , Produce dark or bright colors be based on YUV The mode determines the brightness of the color

    .NET C# Generate random colors , You can control the brightness , Produce dark or bright colors be based on YUV The mode determines the brightness of the color   Random colors are often used in daily development , Sometimes you have to control the brightness of the color , For example, random colors on white background pages , Generally, the color should be a little darker ...


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved