Python learning-Object-oriented learning

Source: Internet
Author: User
Tags class definition function definition

Introduction to Object Orientation

OOP programming is the use of "class" and "object" to create a variety of models to achieve a real-world description, the use of object-oriented programming because it can make the maintenance and extension of the program easier, and can greatly improve the efficiency of program development, in addition, An object-oriented program can make it easier for people to understand your code logic and make team development easier.

Three main features of object-oriented

Encapsulation Package
Encapsulate objective things into abstract classes, and classes can put their own properties and methods only trusted classes or objects to operate, to the untrusted information hiding.
The note is. The properties described here are not just basic data types, but also reference data types, which means that we can also encapsulate objects of other classes in a class so that they implement the corresponding method of referencing the class in this class.

Inheritance inheritance
First, what does inheritance mean? From the understanding that the son has acquired the father all things, and these things belong to the son, the son can arbitrarily dominate. From a programming language perspective, it is a class that acquires all the methods of another class and autonomously dictates these methods. Here, the class that is inherited by others, we call the parent class, also called the superclass or the base class. and inheriting the class of the parent class, it is called a subclass, also called a derived class.
So a class can derive subclasses, and subclasses automatically inherit the properties, methods defined in the parent class.

Polymorphism polymorphism
Polymorphic definition: means that objects of different classes are allowed to respond to the same message. That is, the same message can be used in a variety of different ways depending on the sending object. (Sending a message is a function call)

The technique of implementing polymorphism is called dynamic binding, which is the actual type of the referenced object that is judged during execution, and its corresponding method is called according to its actual type.

Polymorphism is an important feature of object-oriented, simple point: "An interface, a variety of implementations", refers to a base class derived from a different subclass, and each subclass inherits the same method name, but also the parent class method to do a different implementation, this is the same thing shows a variety of forms.

In reality, there are numerous examples of polymorphism. For example, if you press the F1 button, if the current pop-up in the Flash interface is the as 3 help document, if Word Help is currently popping up under Word, Windows Help and Support appears under Windows. The same event occurs on different objects and produces different results. Like sugar, there are a variety of flavors, you want to eat what flavor can eat what taste. But in the program, it's not what you want. It's more about how to do what you need to do. A more official explanation: in object-oriented languages, many different implementations of interfaces are polymorphic.

Programming is actually a process of abstracting the concrete world, which is a manifestation of abstraction, abstracting the common denominator of a series of specific things, and then through this abstract thing, and dialogue with different concrete things.
Sending the same message to different classes of objects will have different behavior. For example, if your boss lets all employees start working at nine o'clock, he says "get started" at nine o'clock, instead of saying to the salesperson: "Start a sales job," say to the technician, "Start technical work", because "employee" is an abstract thing, so long as the employee can start to work, He knows that. As for each employee, of course, they do their job and do their jobs.
Polymorphism allows the object of a subclass to be used as an object of the parent class, a reference to a parent type to an object of its subtype, and the method called is the method of that subtype. The code that references and invokes the method is already determined before it is compiled, and the object pointed to by the reference can be dynamically bound during run time

Encapsulation 1. Classes and objects

Class
A class is an abstraction, a blueprint, a prototype for a class of objects that have the same properties. The properties of these objects (variables (data)) and common methods are defined in the class.
The abstraction of things out of class, that is, encapsulation.

Object objects
An object is an instantiated instance of a class, that is, an instance of the class. A class must be instantiated before it can be called in a program, a class can instantiate multiple objects, and each object can have different properties, as human beings refer to everyone, everyone refers to specific objects, people and people before the common, there are different

Python uses class reserved words to define classes, and the first letter of the class name must be capitalized.

For the Student class, for example, in Python, the definition class is through the Class keyword: class Student (object): Passclass followed by the class name, which is Student, the class name is usually the beginning of the word in uppercase, followed by (object), Indicates which class the class inherits from, and the concept of inheritance we will say later, usually, if there is no suitable inheriting class, use the object class, which is the class that all classes eventually inherit. Once you have defined the Student class, you can create an instance of Student based on the Student class, and create an instance that is implemented through the class name + ():>>> Bart = Student () >>> bart<__main__ . Student object at 0x10a67a590>>>> student<class ' __main__. Student ' > You can see that the variable Bart is pointing to an instance of Student, the 0x10a67a590 is the memory address, the address of each object is different, and the Student itself is a class. You are free to bind attributes to an instance variable, for example, Bart binds a Name property:>>> Bart.name = ' Bart Simpson ' >>> bart.name ' Bart Simpson ' Because a class can act as a template, you can force a number of attributes that we think must be bound to be filled in when creating an instance. By defining a special __init__ method, when creating an instance, bind the attributes such as Name,score: Class Student (object): Def __init__ (self, Name, score): Self.nam E = name Self.score = Score Note: There are two underscores before and after the special method "__INIT__"!!! Note that the first parameter of the __init__ method is always self, which represents the created instance itself, so that within the __init__ method, various properties can be bound to self, because the individual points to the created instance itself. With the __init__ method, when you create an instance, you cannot pass in an empty argument, you must pass in a parameter that matches the __init__ method, but self does not need to be passed, and the Python interpreter will pass the instance variable in itself:>>> Bart = Student (' Bart Simpson ', ' I ') >>> bart.name ' Bart Simpson ' >>> bart.score59 

A function defined in a class is only a bit different than a normal function, which is that the first argument is always the instance variable self and, when called, does not pass the argument. In addition, there is no difference between a class method and a normal function, so you can still use default parameters, variable arguments, keyword arguments, and named keyword parameters.
Note:Self represents an instance of a class, not a Class!

2. There are two types of instance properties and Class attribute properties: Instance properties, Class properties.

Instance properties are defined in the constructor Init and are prefixed with self when defined.
Class properties are defined outside of a method in a class.
Instance properties belong to an object (instance) and can only be accessed by the object name after instantiating the object. Class properties are classes that can be accessed directly from the class name without instantiating the object (although you can also access the class properties through an object, it is not recommended, because doing so will result in inconsistent class property values). Class properties can also be added to the program by the class name, such as the class name, after the class definition. class Property = value

Common Properties and private properties

Property names that start with a double underscore are private properties, otherwise they are common. Private properties cannot be accessed directly outside the class. But Python provides a way to access private properties that can be used for program testing and debugging. Here's how:

对象名.__类名+私有属性名字

For example:

class People(object):    def __init__(self,name,money):        self.name = name        self.__money = moneyp1 = People(‘user1‘, 1000000)p1.__People__money = 999999 #访问私有属性并修改~print(p1.__People__money)
3. Methods of the class

Methods of the class:
Inside the class, you define a method using the DEF keyword, which differs from the general function definition in that the class method must contain the parameter self, which is the first argument, and self represents the instance object of the class.
The name of self is not immutable (because it is a formal parameter), but it can also be used, but it is best to use self as a convention.

Public methods and Private methods

Public methods, private methods belong to objects, and each object has its own public method, private method. Public methods are called through object names, and private methods cannot be called by object names, but only by self in methods that belong to the object, which can only be called inside the class and cannot be called outside the class.
Two underscores begin, declaring that the method is a private method. The public method is simply to write a method name.

class method, static method

1. The class method is implemented through the @classmethod adorner, the difference between a class method and a common method is that the class method can only access the class variable and cannot access the instance variable

class Dog(object):    def __init__(self,name):        self.name = name    @classmethod    def eat(self):        print("%s is eating" % self.name)d = Dog("hahaha")d.eat()

The execution error is as follows, saying that dog does not have a name attribute because name is an instance variable and the class method cannot access the instance variable.

Traceback (most recent call last):  File "/Users/jieli/PycharmProjects/python_projects/面向对象/类方法.py", line 9, in <module>    d.eat()  File "/Users/jieli/PycharmProjects/python_projects/面向对象/类方法.py", line 6, in eat    print("%s is eating" % self.name)AttributeError: type object ‘Dog‘ has no attribute ‘name‘

At this point you can define a class variable, also called name, to see the execution effect

class Dog(object):    name = "hahahahahahaha"    def __init__(self,name):        self.name = name    @classmethod    def eat(self):        print("%s is eating" % self.name)d = Dog("hahaha")d.eat()运行输出:hahahahahahaha is eating

2. The decorative method can be changed to a static method by @staticmethod the adorner. An ordinary method, which can be called directly after instantiation, And in the method can pass self. Invokes an instance variable or a class variable, but a static method cannot access an instance variable or a class variable, and a method that cannot access an instance variable or a class variable is, in fact, nothing to do with the class itself, and its only association with a class is the need to call this method through the class name

class Dog(object):    def __init__(self,name):        self.name = name    @staticmethod #把eat方法变为静态方法    def eat(self):        print("%s is eating" % self.name)d = Dog("hahaha")d.eat()

The above call will have the following error, saying that eat needs a self parameter, but the call is not passed, yes, when the eat becomes a static method, and then through the instance call will not automatically pass the instance itself as a parameter passed to the auto.

Traceback (most recent call last):  File "/Users/jieli/PycharmProjects/python_projects/面向对象/静态方法.py", line 9, in <module>    d.eat()TypeError: eat() missing 1 required positional argument: ‘self‘

There are two ways to make the above code work correctly

1. When invoked, the instance itself is passed to the Eat method, i.e. D.eat (d)

class Dog(object):    def __init__(self,name):        self.name = name    @staticmethod #把eat方法变为静态方法    def eat(self):        print("%s is eating" % self.name)d = Dog("hahaha")d.eat(d)运行输出:hahaha is eating

2. Remove the self parameter in the Eat method, but this also means that you cannot pass self in eat. Calls to other variables in the instance

class Dog(object):    def __init__(self,name):        self.name = name    @staticmethod    def eat():        print(" is eating")d = Dog("hahaha")d.eat()运行输出: is eating
Property method

The function of a property method is to turn a method into a static property by @property

class Dog(object):    def __init__(self,name):        self.name = name    @property    def eat(self):        print(" %s is eating" %self.name)d = Dog("hahaha")d.eat()

The call will be the following error, said Nonetype is not callable, because eat at this time has become a static property, not a method, want to call already do not need to add () number, direct d.eat can be

Traceback (most recent call last): ChenRonghua is eating  File "/Users/jieli/PycharmProjects/python_projects/面向对象/属性方法.py", line 8, in <module>    d.eat()TypeError: ‘NoneType‘ object is not callable

The normal call is as follows

d = Dog("hahaha")d.eat输出 hahaha is eating

The next blog will cover the details of @property, this is only a brief introduction
Also refer to the blog: http://www.cnblogs.com/alex3714/articles/5213184.html

Inheritance 1. Single inheritance

As the name implies, single inheritance refers to subclasses inheriting only one parent class.

#定义类class People:    #定义基本属性    name = ‘‘    age = 0    #定义私有属性,私有属性在类外部无法直接进行访问    __weight = 0    #定义构造方法    def __init__(self,n,a,w):        self.name = n        self.age = a        self.__weight = w    def speak(self):        print("%s 说: 我 %d 岁。" %(self.name,self.age))#单继承class Student(people):    grade = ‘‘    def __init__(self,n,a,w,g):        #调用父类的构函        People.__init__(self,n,a,w)                #或者用super方法                #super(People, self).__init__(n,a,w)        self.grade = g    #覆写父类的方法    def speak(self):        print("%s 说: 我 %d 岁了,我在读 %d 年级"%(self.name,self.age,self.grade))s = Student(‘ken‘,10,60,3)s.speak()
2. Multiple inheritance

Subclasses inherit multiple parent classes at the same time

  #类定义class People: #定义基本属性 name = ' age = 0 #定义私有属性, private properties cannot be accessed directly outside the class __weight = 0 #定义构造方法 def __init__ (self,n,a,w): Self.name = n Self.age = a self.__weight = W def speak (self): PRI NT ("%s" said: I'm%d years old.) "% (self.name,self.age)) #单继承 class Student (people): Grade =" Def __init__ (self,n,a,w,g): #调用父类的构函 P eople.__init__ (self,n,a,w) Self.grade = G #覆写父类的方法 def speak (self): print ("%s said: I'm%d years old, I'm reading grade%d"% (s        Elf.name,self.age,self.grade)) #另一个类, the preparation of multiple inheritance before class Speaker (): topic = ' name = ' def __init__ (self,n,t): Self.name = n Self.topic = t def speak (self): print ("My name is%s, I am an orator, I am speaking the subject of%s"% (self.name,self.topic)) #多 Inherit class Sample (speaker,student): a = "def __init__ (self,n,a,w,g,t): student.__init__ (self,n,a,w,g) Sp eaker.__init__ (self,n,t) test = Sample ("Tim", 25,80,4, "Python") Test.speak () #方法名同, the default is to call the method  
in parentheses before the parent class.

Classic class and New class

      经典类的继承算法: 深度优先算法      新式类的继承算法: 广度优先算法

Python3 are all new types
There are both new and classic classes in Python2.

    • After the inheritance, through the subclass of the object call a method, if the subclass is not, then go to the parent class, if the parent class is not, then an error.
    • Private properties, private methods, which are accessible inside the class, are not accessible to the outside or subclass of the class
Polymorphic

Pyhon Many grammars support polymorphism, such as Len (), Sorted (), and so on, you give Len a string to return the length of the string, and the list returns the length of the list.

About polymorphism, Liaoche Teacher's tutorial is easy to understand, here is attached address: inheritance and polymorphic reference articles
Also attached is an object-oriented explanation of the old boy Python3 tutorial, because he finally talked about the domain model: Portal

Finally on polymorphism, intercept Liaoche teacher's little explanation:
Static language vs Dynamic Language

For a static language (for example, Java), if you need to pass in a animal type, the incoming object must be a animal type or its subclass, otherwise the run () method cannot be called.

For dynamic languages such as Python, it is not necessarily necessary to pass in the animal type. We just need to make sure that the incoming object has a run () method on it:

Python learning-Object-oriented learning

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.