Python---object-oriented programming

Source: Internet
Author: User

process-oriented programming (Baidu or Google):

  (1) Definition:

(2) Compare the advantages and disadvantages of functional and process-oriented programming:

Classes in Python:

(1) definition (Baidu or Google):

  (2) Description: The classes in Python consist of properties and methods, and methods in the class are used or modified for the property. Compared to characters in the game, there are strength values, spell values, object defense, anti-defense and other properties, and the skill of the game character is to use these attributes, the game role of the upgrade or drop will modify these values, for the class, its skills are methods, these methods or modify or use the properties of the class.

  (3) Application: class is generally an abstract modeling of a real object, it is used in computer programs in batches to produce such things. Just like in the game, a role, there are thousands of players use, due to the level of each player, equipment and other differences, attribute values are different, but the attributes of these characters are the most basic composition (strength value, spell value, object defense, law prevention, etc.), the role of the skill effect is the same, For classes, you can create them in batches in a program by simply modifying the underlying properties.

  (4) syntax for classes in Python:   

classPerson (object): Ethnicity="Humanity"    def __init__(self, name, age, wages):" "constructors, which initialize the properties of an object" "Self.name=name self.__age= Age#Private PropertiesSelf.wages =WagesPass    def __del__(self):" "destructor , executed when the object is destroyed or the program ends" "        Print("__del () __")        Pass    deffunc1 (self):" "The first method, showing the use of attributes" "        Print("This is func1 ()")        Print("%s:age:%s wages:%s"% (Self.name, self.__age, Self.wages)) Pass    defFunc2 (self):" "The second method, which shows the modification of the property" "Self .__age+ = 1self.wages-=1500Print("This is Func2 ()")        Print("%s:age:%d wages:%d"% (Self.name, self.__age, Self.wages)) Pass    defGet_info (self):Print("name:%s\nage:%s\nwages:%s\nethnicity:%s"% (Self.name, self.__age, Self.wages, self.ethnicity)) Person_1= Person ("Jack", 21, 10000)#instantiate a person with a classPrint(Person_1.name)#calling properties in a classPERSON_1.FUNC1 ()#calling methods in a classPerson_1.func2 () person_1.get_info ( )>>>Jackthis isfunc1 () Jack:age:wages:10000 This isFunc2 () Jack:age:wages:8500name:jack #get_info执行结果 Age:22Wages:8500
Ethnicity:humanity__del() __ #析构函数执行结果

In this example, the most basic and simple modeling of a person's use of a class demonstrates the syntax and application of classes in Python.

Constructor: A basic property used to initialize an object. For example, in this example the object (name, age, wages) three basic properties, with the constructor for the initial assignment.

Class Property: A variable that is defined above a constructor. Common properties of objects that are generally manufactured in batches (and are not often changed) are defined in this way. (such as the race, occupation, etc.) of a game character.

Instance properties: Variables defined in the constructor. The difference attribute of a batch-generated object or the default attribute that may be changed frequently (implemented in default parameters) is defined in this way. (e.g. player's nickname, rank, etc.)

Destructor: Executes automatically when an object is destroyed or when the program ends. Typically used to turn off temporary files or database connections that are opened by other methods in the class.

Private properties: can only be modified or queried by methods in the class and cannot be accessed outside of the class. Simply add ' __ ' to the variable name in the definition, and you can use the same method to define the private method (add ' __ ' before the function is used, generally for the lower-level method of some methods in the class, which cannot be called externally). In this case, __age is a private property that cannot be used in this way like Person_1.name.

(5) Inheritance and derivation of classes:

classPerson (object): #本例中的基类def __init__(self, name, gender, age): Self.name=name Self.gender=Gender Self.age= Agedefmy_message (self):Print(" "-----Message of%s-----name:%s gender:%s age:%s" "%(Self.name, Self.name, Self.gender, self.age))classWorker (person):#worker class inherits person class    def __init__(self, name, gender, age, wage): Super (Worker, self).__init__(name, gender, age)#call the constructor of the parent class and call the other methods of the parent class simply to change the function name and parameterSelf.wage =wagedefGet_paid (self):Print("my wage: $%s"%self.wage)classDriver (Worker):#Driver class inherits worker class    def __init__(self, name, gender, age, wage, driving_age): Super (Driver, self).__init__(name, gender, age, wage) Self.driving_age=Driving_agedefDrive (self):Print("My driving age is%s years", Self.driving_age)Print("Driving ...")Print("First Class") P1= Person ("John",'M', 35) p1.my_message ()#calling in-class methodsPrint('\ n')Print("Second Class") W1= Worker ("Lily",'F', 30, 5000) w1.my_message ()#calling the parent class methodW1.get_paid ()#calling in-class methodsPrint('\ n')Print("Third Class") D1= Driver ("Jack",'M', 40, 7500, 15) d1.my_message ()#calling the parent class of the parent class methodD1.get_paid ()#calling the parent class methodD1.drive ()#calling in-class methods>>>First Class-----Message of John-----Name:john gender:m Age:35Second Class-----Message of Lily-----name:lily gender:f Age:30My wage: $5000Third Class-----Message of Jack-----name:jack gender:m Age:40My wage: $7500My Driving Age is%s Years 15Driving ...

Description: Like the awakening of a game character (or a career change), it often adds new attributes and skills to the original character base. This is also the same operation in the class, called the inheritance and derivation of the class. If the class in the program only inherits, it is better to use the original class directly, so there is a derivation of inheritance in general. The role of inheritance and derivation is to add new attributes and new methods to the class.

Worker class: The worker class inherits the person class, compared with the base class he adds an attribute (wage) and a method (Get_paid ())

Driver class: Similarly inherited worker class, added an attribute (Driving_age) and a method (drive ())

You can see that the worker class can use its own properties and methods, and it can also use the properties and methods of the parent class, which is similar to a classification of reality under a variety of more detailed categories. In reality, people are a general category, the following can be separated workers, white-collar, civil servants, entrepreneurs and so on, and workers can be separated from oil workers, railway workers, sanitation workers and so on, but top-down, they all have commonalities, bottom-up, they are different. and the computer program to the real world to smoke like so there is the inheritance and derivation of the class.

Instead of observing the driver class, it can use both its own and the parent class's properties and methods, as well as the properties and methods of the parent class's parent class (which can be said to be inherited by alternate generations). So, we can know that a class can inherit more than one generation, and no matter how many generations it inherits, it can use the first generation of the class to any of its own methods or properties.

Note: If a property or method in a subclass is the same as in a parent class, whichever is in the subclass, it is like a global variable and a local variable. (class is the most important part of object-oriented, we should study computer programs carefully.) )

(PS: Because I am still a student, found around many computer professional students interested in learning program code is weak, do not want to contact the code, so the current blog to simplify the code, for libraries, built-in functions, etc. are the most simplified use of the most common way,

For concepts, definitions, etc. in the simplest way, try to avoid the official jargon to inspire the interest of beginners. Because my level is limited, inevitably has the mistake to appear, hoped to point out the correction, the common study progress. )

Python---object-oriented programming

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.