Python Basics-Seventh-7.1 Primary classes and objects

Source: Internet
Author: User

Creating Classes and objects

At first we had a lot of contact programming for process-oriented programming, which was based on business logic from top to bottom code, and then functional programming, is to improve the reusability of code, reduce the workload of the program ape--and today we will learn

Object-oriented programming is implemented using classes and objects, a template in which a template can contain multiple functions that implement functions

Objects are instances created from templates that can execute functions in a class through an instance object

  

    • Class is a keyword that indicates that classes
    • Create object--parentheses after the class name
#创建类class foo:    def bar (self):        print (' Bar ')    def hello (self,name):        print (' I am%s '%name) # Create an object based on class foo ohjobj = foo () obj.bar ()  #执行bar方法obj. Hello (' Alex ')  #执行hello函数

Then you might think: it's not as easy as programming a function??

    • Object-oriented-create object, through object execution method, see that there is a permission on the method execution, only the object has this permission
    • Function Programming: Only call can, can say no permission, no matter who call all to
    • Conclusion: Functional application scenarios, where individual functions are independent and have no shared data

Object-oriented three major features

Object-oriented has three magical functions: encapsulation, inheritance, polymorphism

First, the package

Encapsulation--a good understanding, a literal understanding, what to seal in a place, like: the human organs encapsulated in the body of the sample, so the package characteristics are:

    • Encapsulate content somewhere
    • To invoke the encapsulated content from somewhere

The first performance--encapsulating content somewhere

Second performance: Calling encapsulated content from somewhere

    • Called directly through an object
    • Indirectly called through self

Well, encapsulation is like this, encapsulating some attributes to an object and then invoking it directly with the object, or self indirectly, simply

Ii. inheritance

Inheritance--the same as the inheritance in life, namely: the child can inherit the father's skills

As an example:

Cats can: Meow meow, eat and drink and sprinkle

Dogs can: bark, eat and drink and scatter.

We can obviously find that dogs and cats will eat and drink, not only dogs and cats will, is an animal will, if you want to write this two classes, eat and drink to write two times, the inheritance of the characteristics is to facilitate our

Class Animal:    def Eat (self):        print ('%s eat '%self.name)    def drink (self):        print ('%s drink '%self.name)    def shit (self):        print ('%s pull '%self.name)    def pee (self):        print ('%s scatter '%self.name) #在类后面括号中写入另外一个类名, Indicates that the current class inherits another class Cat (animal):    def __init__ (self,name):        self.name = name        self.breed = ' cat '    def Cry ( Self):        print (' Meow meow ') class Dog (animal):    def __init__ (self,name):        self.name = name        self.breed = ' dog '    def Cry (self):        print (' barking ') C1 = Cat (' Small White House's little Black Cat ') c1.eat () D1 = Dog (' Fat House's Little Skinny Dog ') d1.drink ()

Therefore, for object-oriented inheritance, it is actually the method of extracting multiple classes common to the parent class, the subclass only need to inherit the parent class without having to implement each method, in addition to the parent class and subclass of the title, can also be called base class and derived class

The question comes again, can you inherit multiple classes? If the same function is defined in multiple classes where inheritance is encountered, which is performed?

1. Python classes can inherit multiple classes, and Java and C # can inherit only one class

2. If the Python class inherits more than one class, there are two ways to find the method: Depth First and breadth First

    • When a class is a classic class, multiple inheritance cases are searched in the depth-first way
    • When a class is a new class, in multiple inheritance cases, the breadth-first method is found

Classic class and new class, literally can see an old a new, the new must contain with many functions, but also after the recommended wording, from the wording of the words, if the current class or the parent class inherits the object class , Then the class is the new class, otherwise it is the classic class.

#多继承 # Classic class classmate (): Def __init__ (self,name): Self.name = name def eat (self): print ('%s is eatin G. '%self.name) def drink (self): print ('%s is drinking. ') %self.name) #派生类1: Class female (classmate): Def drink (self): print ('%s drink orange juice '%self.name) #派生类2: Class M Ale (Classmate): Def drink (self): print ('%s is drink alcohol '%self.name) class Pythoner (classmate): Def Occupti On (self): print ('%s is a pythoner. ') %self.name) class Fe_pythoner (Pythoner,female): Passclass Ma_pythoner (pythoner,male): Passeva = Fe_pythoner (' Eva ') Eva  . drink () Sweet = Ma_pythoner (' Sweet ') Sweet.drink () #新生类class classmate (object): Def __init__ (self,name): Self.name = Name Def eat (self): print ('%s is eating. ') %self.name) def drink (self): print ('%s is drinking. ') %self.name) class female (classmate): Def drink (self): print ('%s drink orange juice. ') %self.name) class male (classmate): Def drink (self): print ('%s driNK alcohol. ' %self.name) class Pythoner (classmate): Def occupation (self): print ('%s is a pythoner. ') %self.name) class Fe_pythoner (Pythoner,female): Passclass Ma_pythoner (pythoner,male): Passeva = Fe_pythoner (' Eva ') Eva . drink () Sweet = Ma_pythoner (' Sweet ') Sweet.drink () #结论: In Python3, the inheritance of a class is by default the breadth first # in Python2, the classic class is more inherited, in depth first lookup, New type multi-inheritance by breadth first search

Another subclass inherits the construction method of the parent class:

Class Fund (object):    def __init__ (self,fund_type,fund_name):        self.fund_type = fund_type        self.fund_name = Fund_name    def Chao (self):        passclass index_fund (Fund):    def __init__ (Self,fund_type,fund_name,nav):        Super (Index_fund,self) __init__ (fund_type,fund_name)        Self.nav = Nav    def cao (self):        pass    def Prin (self):        print (' {} was {},now Jingzhi is {} '. Format (self.fund_name,self.fund_type,self.nav)) obj1 = Index_fund ( ' Index fund ', ' Phu Quoc, 2.2 ', Obj1.prin ()

Three, polymorphic

Pyhon does not support polymorphism and is not polymorphic, the concept of polymorphism is used in strongly typed languages such as Java and C #, while Python advocates "duck type".

Class F1:    passclass S1 (F1):    def Show (self):        print ' S1.show ' class S2 (F1):    def Show (self):        print ' S2.show ' # Because of defining function parameters in Java or C #, you must specify the type of the parameter # in order for the Func function to execute the Show method of the S1 object, and to execute the Show method of the S2 object, the parent class of the S1 and S2 classes is defined # The actual parameters passed in are: S1 object and S2 object def Func (F1 obj):    "" "Func function needs to receive a F1 type or F1 subclass of type" "" "        print Obj.show ()    s1_obj = S1 () func (s1_obj) # Pass in the S1 class object S1_obj in the Func function, execute S1 's Show method, result: S1.shows2_obj = S2 () func (s2_obj) # passed in the Func function to the SS class object Ss_obj, performing the SS show method, Result: S2.show

Class F1:    passclass S1 (F1):    def Show (self):        print ' S1.show ' class S2 (F1):    def Show (self):        print ' S2.show ' def Func (obj):    

How classes and objects are stored in memory

  Classes and methods in the class have only one copy in memory, and each object created by the class needs to be stored in memory

As shown, when you create an object from a class, the object, in addition to encapsulating the value of name and age, holds a class object pointer that points to the class of the current object.

When "method One" is executed through OBJ1, the process is as follows:

      1. Finds a method in a class based on the pointer to a class object in the current object
      2. obj1 The object as a parameter to the first argument of the method self

You are welcome to ask questions and questions about my blog content! Thanks

Author: Pat Province Mr.

Python Basics-Seventh-7.1 Primary classes and objects

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.