11. Object-Oriented Programming

Source: Internet
Author: User
Tags what inheritance
11. Object-Oriented Programming

Python and Java are object-oriented languages, so we need to learn how to define and use classes. First, we need to know that the class is defined using the keyword class. For example:

#!/usr/bin/pythonclass Demo:       pass #empty class

Well, we have learned how to define a class. Now that we have defined a class, we have to learn how to use the class. So how do we use classes? First, we need to instantiate the class, that is, we need to create a variable of the class type that we have defined. Then, we use the class by calling and modifying the class attributes. Therefore, we must first know how to create a class-type variable. Creating a class-type variable is actually very simple. We only need to call the class just like calling a function to create a class-type variable. Oh, this is a tangled sentence. In fact, you will understand an example:

C = demo () # We have defined a variable named C for a class called demo.

I can't believe that we have a class type variable in this simple way. Let's use it now. So what are the attributes of a class? The variables and functions that belong to the class are collectively referred to as the class attributes. In the class, we create a new name for the variables and functions that belong to it. The variables that belong to the class or object are called fields, and the functions that belong to the class or object are called methods.

Since we use the class attributes, we must know how to define the domain and method in the class before using the class. As we can imagine, this is actually no big difference from the variables and functions previously defined, but it does not mean that there is no difference. Take a look at the following code:

#!/usr/bin/pythonclass Demo:       defmethod(self):              print 'this is a method'

Well, we have defined a method for the class. Then we can use

Variable name. Method Name (parameter list)

. For example:

C = demo ()

C. Method ()

This will display this is method on the screen.

No matter whether you have noticed it or not, the difference has emerged. In fact, it is obvious that when defining a method, we define a parameter called self for the method, which must be placed first. It doesn't matter whether this parameter is called self. However, we strongly recommend that you use the self name, which is a habit in Python, whether you read other people's code or others read your code, you will see at a glance that this is a method defined for the class. The meaning of this parameter is to tell you that "this is my method ". That is, when you call a class method, the interpreter converts the method call

Class Name. Method Name (variable name, parameter list)

To convert C. Method () to demo. Method (c. In addition, when calling a method defined in a class, you must add a "self." prefix before the method. For example, we define a callmethod method to call the method in the demo class:

#!/usr/bin/pythonclass Demo:       def method(self):              print 'this is a method'       def callmethod(self):              self.method()c = Demo()c.callmethod()

Display: This is a method

Let's take a look at the question about the variable-field of a class or object. Here we need to know that the domain is also divided into two types: class variables and object variables.

Class variables:

All variables of this type share the same variable. When an instance changes the value of a class variable, the value of this attribute of other instances also changes. This type of variable is defined in the class and used for calling.

Class Name. Domain Name

.

Object variable:

Each type variable has a copy of this type of variable. The value of this type of variable in each instance does not affect each other. That is to say, instances do not share this type of variable, these variables are independent of each instance. Modifying such variables does not affect the attribute values of other instances. These variables are defined in the _ init _ () method and prefixed with "self.". They are used for class calls.

Object Name. Domain Name

In the same way as calling a method in the class, add the prefix "self.

The following is an example:

#!/usr/bin/pythonclass Obj:       objNum = 0       def __init__(self, data):              self.data =  data              print 'data is', datao = Obj(1)print Obj.objNumo2 = Obj(1)print Obj.objNum

Display:

Data is 1

1

Data is 1

2

I think you may still be confused about the _ init _ () method. Let's take a look at this function now. The _ init _ () method is a special method. This method is the half method defined by python. Why is it half? Because this function must be called _ init __and must be completed by ourselves, the function will be automatically called when defining a class type variable, use the data in the parameter list and initialize the data (object variables) inside the class. Init is the first four letters of English word initialization. If you have learned C ++ or Java, you will know that this function is equivalent to a constructor. There are many functions such as _ Inti _. For example, the _ del _ function is called when the variable ends its life cycle, which is equivalent to the destructor in C ++.

Next, let's take a look at an indispensable mechanism in the face of objects-inheritance. So what is inheritance? Why? How? And when?

Oh, there are quite a few questions. First, let's take a look at what inheritance means, simply literally. Just like human children will learn from their elders (such as their parents) where to inherit some features, the class can also inherit some things from other classes, and these things are the attributes of the class.

Why inherit? This is to simplify programming and bring our thinking closer to real life.

Why? For example, we need to use the object-oriented method to write an animal game. Therefore, we need to define different classes for different animals, animals are classified into the same category because they have many similarities. Since there are many similarities between animals, it is not a waste of time to write the same attributes for every animal. In this case, inheritance comes in handy. we can write a class called animal, in which we can write the same and similar characteristics of animals, then we only need to inherit the animal class when writing other animals and define the unique characteristics and features of the animal in the class of the animal, so that we can reduce a lot of work, at the same time, the regulations are clear and more in line with our real life thoughts.

The inherited animal class is called a parent class or a superclass, while other animal classes inherited from the animal class are called a derived class or a subclass. However, each type of animal has its similarities. For example, the call of an animal is called, so we can define a makenoise function in the animal class to indicate the occurrence of an animal, however, the sound of each animal is different, such as dogs and cats. Therefore, we can define the makenoise function in the dog and cat classes, this function prints the sounds of dogs and cats. In this way, the method that defines the existing methods in the parent class in the subclass is called the function overload. in Python, like in C ++, not only function overloading can be performed, it can also be used to reload most operators (not described here ).

Since inheritance is so good, we will immediately learn how to implement inheritance. In fact, implementation inheritance is very simple. If you add a tuple containing the parent class list after the class name when defining the class, you can inherit the classes listed in tuple. That's right. You didn't see that not only can inherit a class, but python can inherit more. At the same time, you don't have to worry about a fatal Square. The so-called fatal square means that the class inherited by a Class inherits the same class, and python will handle it for you.

Finally, this is the most important thing. It is also property and inheritance. When should we use inheritance and when should we use it? The answer is to use the famous is-a and has-. This seems very esoteric. Actually, learning through examples is always the best learning method. Let's look at an example. Dogs are (is-a) animals (animal), so the dog class can inherit the animal class; dogs have (has-a) tails, so the tail is the property of dogs. How is it? Is it clear?

Woo ~ After talking so much, I can finally look at the example. Thank God! As I said, learning through examples is always the best way to learn. Let's look at an example that is different from animals but closer to life: defines students and teachers. Students should include the name, age, and total score of the current semester, teachers should include names, ages, and monthly salary, and calculate the total number of students plus teachers ).

Because both students and teachers are members of the school and both attributes are named and age, we can define a schoolmember class as the parent class. The Code is as follows:

#!/usr/bin/pythonclass SchoolMember:       def __init__(self, name, age):              self.name= name              self.age= age       def tell(self):              print 'Name: %s\nAge: %e' % (self.name, self.age)class Teacher(SchoolMember):   '''Represents a teacher.'''    def __init__(self, name, age, salary):       SchoolMember.__init__(self, name, age)       self.salary = salary       print '(Initialized Teacher %s)' % self.name    def tell(self):       SchoolMember.tell(self)       print 'Salary: "%d"' % self.salary class Student(SchoolMember):    def__init__(self, name, age, marks):        SchoolMember.__init__(self,name, age)        self.marks= marks        print '(Initialized Student %s)' % self.name    def tell(self):        SchoolMember.tell(self)            print 'Marks: "%d"' % self.markst = Teacher('Mrs. Shrividya', 40, 3000)s = Student('Swaroop', 22, 75)print # prints a blank linemembers = [t, s]for member in members:    member.tell() # works for both Teachars and Students

This example is a good summary of the chapter, and also tells us that we need to use

Parent class name. domain name or parent class name. Method Name (self, parameter list)

To call the attributes of the parent class. If the attribute is a function, add self to the first position in the parameter list. Before the end, you must mention that in C ++ or Java, there will be private members, protected members, and public members respectively, it also has access permissions and attributes such as private inheritance, public inheritance, and inheritance protection virtual functions. However, python is not so complex. In python, there are only public members, public inheritance, and virtual functions. However, in Python, there is an unwritten habit of processing attributes with an underline prefix before the name as private members. Because this effective private member case already exists, Python only provides support for a limited private member mechanism, called name reorganization. The variable whose name starts with a double underscore (at least two underscores and at most one underscore) will be replaced

_ Class name__ variable name

. This mechanism ignores the location of identifiers. As long as such names occur, name reorganization will take effect.

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.