Python object-oriented learning notes

Source: Internet
Author: User
Tags export class inheritance in python


To create a class:


#!/usr/bin/python
# Filename:simplestclass.py

Class Person:
Pass # a empty block

p = person ()
Print P
$ python simplestclass.py
<__main__. Person instance at 0xf6fcb18c>

We use the class name followed by a pair of parentheses to create an object/instance. For verification, we simply printed the type of the variable. It tells us that we already have an instance of the person class in the __main__ module.
You can note that the computer memory address of the storage object is also printed out. This address will be a different value on your computer because Python can store objects in any vacancy.

Method in the object

We have discussed that classes/objects can have methods like functions, and that the difference between these methods and functions is only an extra self variable. Now we're going to
Learn an example.


#!/usr/bin/python
# Filename:method.py

Class Person:
def sayhi (self):
print ' Hello, how are you? '

p = person ()
P.sayhi ()
$ python method.py
Hello, how are are you?

Here we see the use of self. Note that the Sayhi method does not have any arguments, but it still has self when the function is defined.

__init__ Method:

The __init__ method runs immediately when an object of the class is established. This method can be used to do some of the initialization you want for your object.


#!/usr/bin/python
# Filename:class_init.py

Class Person:
def __init__ (self, name):
Self.name = Name
def sayhi (self):
print ' Hello, my name is ', Self.name

p = person (' Swaroop ')
P.sayhi ()
$ python class_init.py
Hello, my name is Swaroop

Methods of classes and objects

We've talked about the functional parts of classes and objects, and now let's take a look at its data section. In fact, they are just ordinary variables bound to the namespace of the class and object, that is, these names are valid only for those classes and objects.
There are two types of domains-the variables of the class and the variables of the object, which are differentiated according to whether the class or object owns the variable.
A variable of a class is shared by all objects (instances) of a class. There is only one copy of a class variable, so when an object changes the variables of the class, the change is reflected on all other instances.
The variable of an object is owned by each object/instance of the class. So each object has its own copy of the domain, that is, they are not shared, and in different instances of the same class, although the object's variables have the same name, they are unrelated. An example would make this easy to understand.

Using variables of classes and objects


#!/usr/bin/python
# Filename:objvar.py

Class Person:
"' represents a person. '
Population = 0

def __init__ (self, name):
"' Initializes the person ' s data. '
Self.name = Name
print ' (initializing%s) '% Self.name

# When this is created, he/she
# adds to the population
Person.population + 1

def __del__ (self):
' I am dying. '
print '%s says bye. '% self.name

Person.population-= 1

If person.population = 0:
print ' I am the last one. '
Else
print ' There are still%d people left. '% person.population

def sayhi (self):
"Greeting by" person.

Really, that's all it does.
print ' Hi, my name is%s '% Self.name

def howmany (self):
"' Prints the current population. '
If person.population = 1:
print ' I am ' is here. '
Else
print ' We have%d persons here. '% person.population

Swaroop = person (' Swaroop ')
Swaroop.sayhi ()
Swaroop.howmany ()

Kalam = person (' Abdul kalam ')
Kalam.sayhi ()
Kalam.howmany ()

Swaroop.sayhi ()
Swaroop.howmany ()
$ python objvar.py
(Initializing Swaroop)
Hi, my name is Swaroop.
I am the only person here.
(Initializing Abdul Kalam)
Hi, my name is Abdul kalam.
We have 2 persons here.
Hi, my name is Swaroop.
We have 2 persons here.
Abdul Kalam says bye.
There are still 1 people left.
Swaroop says Bye.
I am the last one.

Using inheritance:


#!/usr/bin/python
# Filename:inherit.py

Class Schoolmember:
' represents any school member. '
def __init__ (self, Name, age):
Self.name = Name
Self.age = Age
print ' (Initialized Schoolmember:%s) '% Self.name

def tell (self):
"' Tell me details. '"
print ' Name: '%s ' Age: '%s '% (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):
"' represents a student. '
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.marks

t = Teacher (' Mrs Shrividya ', 40, 30000)
s = Student (' Swaroop ', 22, 75)

Print # Prints a blank line

Members = [T, S]
For member in:
Member.tell () # Works for both Teachers and Students
$ python inherit.py
(initialized Schoolmember:mrs. Shrividya)
(initialized Teacher:mrs. Shrividya)
(Initialized Schoolmember:swaroop)
(Initialized Student:swaroop)

Name: "Mrs. Shrividya" Age: "Salary": "30000"
Name: "Swaroop" Age: "Marks": "75"

Python does not automatically invoke the constructor of the base class

Python Object-oriented feature summary


First, packaging

The term object (object) in object-oriented programming can basically be viewed as a collection of data (attributes) and a series of methods that can access and manipulate the data. The traditional meaning of "program = data structure + algorithm" is encapsulated "masking" and simplified to "program = object + Message". An object is an instance of a class, and the abstraction of a class needs to be encapsulated. Encapsulation allows callers to use the object directly without concern about how it is built.

A simple Python class encapsulates the following:


Encapsulation

As you can see from the simple example code above, the classes in Python contain the main elements of a general object-oriented programming language, such as construction methods, binding methods, static methods, attributes, and so on, and if you go deep, you can also find many object-oriented "advanced" topics built into Python, such as iterators, Reflections, Features, and so on, provides a direct structural element of encapsulation.

Second, the succession

1. Class inheritance

The direct feeling of inheriting is that this is the act of reusing code. Inheritance can be understood as a specialized class object based on a common class, and the subclass and its inherited parent class are is-a relationships. A simple but classic example is as follows:


Inheritance

One obvious feature is that Python's object-oriented inheritance features are based on classes (class) and are easier to organize and write code than JavaScript based on prototype (prototype) inheritance, and easier to accept and understand.

PS: In recent days Anders great God out of the typescript turned out, see its language norms inheritance is also based on the class:


Typescript-simpleinheritance

The sense that a class-based inherited language seems to achieve OO readability and programming experience is not bad, according to the legend of JavaScript is the most wanted to spray is the most f**k language.

2. Multiple inheritance

Unlike C#,python, which supports multiple class inheritance (C # can inherit from multiple interface, but most inherit from a class). Multiple inheritance mechanisms can be useful at times, but it's easy to complicate things. An example of multiple inheritance is as follows:


Multinheritance

As you can see, the benefits of multiple inheritance are obvious, and it is easy to construct a type by reusing code in a similar "combination" way.

There is a need to note that if a method inherits from more than one superclass, it is important to be careful about the order of the inherited superclass (or base class):


Multinheritance

We implement a move approach with the same name for both animals and machines, but the output is different in order of inheritance, and the order in which Python accesses the superclass when looking for a given method or feature is called MRO (method resolution order, methods are judged by sequence).

Three, polymorphic

Polymorphism means that you can use the same actions for different objects, but they may present results in a variety of shapes. In Python, polymorphism is used when you don't know what the object is, but you need the object to do something.

The two-paragraph sample code that can directly describe polymorphism is as follows:

1, Method polymorphism


Method-polymorphism

For a temporary object, obj, which is taken out of a random function of Python and does not know the specific type (a string, tuple, or custom type), can call the Count method to compute, and it doesn't matter who (what type) is doing the implementation.

There is something called the "Duck type" (duck typing), which is also polymorphic:


Ducktyping
In terms of the In_the_forest function, the parameter object is a duck type, which implements the method polymorphism. But actually we know that the person type is completely irrelevant to the duck in terms of strict abstraction.

2, operator also polymorphism


Operator-polymorphism

In the example above, it is obvious that the python addition operator is "polymorphic", theoretically, the Add method we implement supports any object that supports addition, but we do not care about the exact type of two parameters x and Y.

The one or two sample code, of course, does not fundamentally describe polymorphism. It is generally believed that the most valuable and underrated feature of Object-oriented is polymorphism. The implementation of the polymorphism we understand is related to the virtual function address binding of subclasses, and the effect of polymorphism is actually associated with dynamic binding of function address runtime. The way to implement polymorphism in C # usually has two kinds of rewriting and overloading, from the above two pieces of code, we can actually analyze the realization of polymorphism in Python can also be interpreted as rewriting and overloading. Many of the built-in functions and operators in Python are polymorphic.

Extra: In C #, we are familiar with interfaces (Interface) and polymorphism correlation, when dealing with a Polymorphic object, it is the basis of an interface (abstraction) in the IOC that does not rely on specific implementation programming, as long as it is concerned about its interface (or "protocol") without explicitly specifying a specific implementation type. Unfortunately there is no interface (abstract class) in Python. In the specification of typescript, the concept of interface is introduced:


Typescript-interface

The definition of interface in the Typescript language specification is the named object type (programmers can give names to object types; We call named object types interfaces. )。 It is directly equivalent to the following ojbect Type:

var Friend: () => {
name:string; FavoriteColor?: string;
};
The JavaScript code equivalent to the above object type in Playgound is as follows:

var Friend;
In the TYPESCRIPT programming specification documentation, some of the instructions for interface:

Interfaces provide the ability to give names to object types and the ability to compose the existing object named into N EW ones.
Interfaces have no run-time representation-they are purely a compile-time construct. Interfaces are particularly useful for documenting and validating the required shape of properties, objects passed as Para meters, and objects returned from functions.

Interface can inherit from interface:


Typescript-interfaceinheritinterface

We tried to get the class to inherit from interface:


Interface Mover
{
Move (): void;
}

Class Simplemover extends mover{
Move () {
Alert ("Move")
}


}

var mover=new simplemover ();
Mover.move ();

The practice proves that the class is not inheritable to implement Interface: A Export class may just extend other classes, Mover are an interface.

Do you now know the difference between the interface in Typescript and the interfaces we know and understand? The same noun interface, the meaning in different contexts is not exactly the same, it may seem silly, but it is almost impossible to learn and use language without contrast.

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.