Classes for Python

Source: Internet
Author: User
Tags export class

1. Self

There is only one special difference between a method of a class and a normal function-they must have an extra first parameter name, but you do not assign a value to this parameter when calling this method, and Python provides this value. This particular variable refers to the object itself, according to the Convention its name is self.

Although you can give this parameter any name, it is strongly recommended that you use the name self-other names are not for you. Using a standard name has many advantages-your program reader can quickly identify it, and some IDES (integrated development environment) can help you if you use self.

You must be wondering how Python assigns to self and why you don't need to assign a value to it. Give an example to make this clear. Suppose you have a class called MyClass and an instance of this class MyObject. When you call this object's method Myobject.method (Arg1, arg2), this is automatically converted from Python to Myclass.method (MyObject, Arg1, arg2)-that's how self works. This also means that if you have a method that does not require parameters, you still have to define a self parameter for this method.

2. Class

#!/use/bin/python

# Filename:simplestclass.py

Class Person:

Pass # an empty block

p = person ()

Print P

[email protected] code]# python simplestclass.py

<__main__. Person instance at 0xb7ee48cc>

A new class is created using the class statement followed by the name of the classes. This is followed by a indented block of statements to form the class body. In this example, we use a blank block, which is represented by a pass statement.

Next, use the class name followed by a pair of parentheses to create an object/instance. (We'll learn more about how to create instances in the following sections.) To verify, we simply printed out the type of the variable. It tells us that we have an instance of the person class in the __main__ module.

You can notice that the 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 empty space.

3. Methods of objects

A class/object can have a function-like method, and the difference between these methods and functions is just an extra self variable. Now let's learn an example.

Ways to use objects:


#!/usr/bin/python

# Filename:method.py

Class Person:

def sayhi (self):

print ' Hello,how is you? '

p = person ()

P.sayhi ()

# This short example can also is written as person (). Sayhi ()

[email protected] code]# python method.py

Hello,how is you?

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

4. __init__ method

The names of many methods in a Python class have special significance. Now we will learn the meaning of the __init__ method.

The __init__ method runs immediately when an object of the class is established. This method can be used to initialize your object with some of the things you want. Note that the start and end of this name are double underlines.

Use the __init__ method:

#!/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 (' RGF ')

P.sayhi ()

# This short example can also is written as person (' RGF '). Sayhi ()

[email protected] code]# python class_init.py

Hello,my name is RGF

Here, the __init__ method is defined as taking a parameter name (as well as the normal argument self). In this __init__, we just create a new domain, also known as name. Note that they are two different variables, although they have the same name. The dot number allows us to differentiate between them.

Most importantly, the __init__ method is not specifically called, but when a new instance of a class is created, the parameters are enclosed in parentheses followed by the class name, which is passed to the __init__ method. This is the important point of this method.

Now, we are able to use the Self.name domain in our methods. This has been verified in the Sayhi method.

5. Methods of classes and objects

The functional part of the class and object has been discussed, and now take a look at its data section. In fact, they are just ordinary variables that are bound to the namespace of the class and object, meaning that these names are valid only for those classes and objects.

There are two types of fields-the variables of a class and the variables of an object-that are differentiated by 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 the class variable, so when an object changes the variables of the class, the change is reflected on all other instances.

The variables of the object are 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 variables of the object have the same name, they are unrelated. Passing an example would make this easy to understand.

Use variables for 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 person 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 is still%d people left. '% person.population

def sayhi (self):

"' greeting by the person.

Really,that ' A all it does. '

print ' Hi,my name is%s. '% Self.name

def howmany (self):

"Print the current population."

if person.population = = 1:

print ' I am the only person here. '

Else

print ' We have%d persons here. '% person.population

RGF = person (' RGF ')

Rgf.sayhi ()

Rgf.howmany ()

Xuan = person (' Xuanxuan ')

Xuan.sayhi ()

Xuan.howmany ()

Rgf.sayhi ()

Rgf.howmany ()

[email protected] code]# python objvar.py

(Initializing RGF)

Hi,my name is RGF.

I am the only person here.

(Initializing Xuanxuan)

Hi,my name is Xuanxuan.

We have 2 persons here.

Hi,my name is RGF.

We have 2 persons here.

Xuanxuan says Bye.

There is still 1 people left.

RGF says Bye.

Here, population belongs to the person class and is therefore a variable of a class. The name variable belongs to the object (it uses the self assignment) and is therefore a variable of the object.

You can see that the __init__ method initializes the person instance with a name. In this method, we let population increase by 1, which is because we have added a person. It is also possible to find that the value of Self.name is specified for each object, which indicates the nature of the variable that it acts as an object.

Remember, you can only use the self variable to refer to the variables and methods of the same object. This is referred to as the attribute reference.

In this program, we also see that docstring is also useful for classes and methods. We can use person.__doc__ and person.sayhi.__doc__ to access the document strings of classes and methods separately at run time.

Just like the __init__ method, there is a special method __del__, which is called when the object dies. When the object dies, the object is no longer in use, and the memory it consumes is returned to the system for its use. In this method, we simply reduce the person.population by 1.

The __del__ method runs when the object is no longer in use, but it is difficult to guarantee when the method will run. If you want to indicate its operation, you have to use the DEL statement, as we used in the previous example.

6. Inheritance

One of the main benefits of object-oriented programming is the reuse of code, and one way to implement this reuse is through inheritance mechanisms. Inheritance can be fully understood as a type and subtype relationship between classes.

Suppose you want to write a program to document the teacher and student situation in the school. They have some common attributes, such as name, age, and address. They also have proprietary attributes, such as teacher salaries, courses and vacations, student grades and tuition fees.

You can create two separate classes for teachers and students to handle them, but in doing so, adding a new common attribute means adding this attribute to the two separate classes. This will soon seem impractical.

A better approach is to create a common class called schoolmember and then let the teacher and student classes inherit this common class. That is, they are all subtypes of this type (class), and then we add proprietary properties to those subtypes.

There are many advantages to using this approach. If we add/change any of the features in Schoolmember, it will automatically be reflected in the sub-types. For example, if you want to add a new domain for both teachers and students, you simply add it to the Schoolmember class. However, changes made within one subtype do not affect other subtypes. Another advantage is that you can use both teachers and student objects as Schoolmember objects, which are particularly useful in certain situations, such as counting the number of school members. A subtype can be replaced with a parent type in any situation where the parent type is required, that is, the object can be considered to be an instance of the parent class, which is called a polymorphic phenomenon.

In addition, we will find that when reusing the code of the parent class, we do not need to repeat it in different classes. And if we use a separate class, we have to do it.

In the above scenario, the Schoolmember class is referred to as the base class or superclass. The teacher and student classes are called export classes or subclasses.

An example program:


#!/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 my 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 (' RGF ', 35,30000)

s = Student (' Xuan ', 5,100)

Print # Prints a blank line


Members = [T,s]

For member in Members:

Member.tell ()

# works for both Teachers and Students

[email protected] code]# python inherit.py

(Initialized SCHOOLMEMBER:RGF)

(Initialized TEACHER:RGF)

(Initialized Schoolmember:xuan)

(Initialized Student:xuan)


Name: "RGF" Age: "Salary": "30000"

Name: "Xuan" Age: "5" Marks: "100"

In order to use inheritance, the name of the base class as a tuple follows the class name when the class is defined. We then notice that the __init__ method of the base class is specifically called with the self variable, so that the basic class part of the object can be initialized. This is very important--python does not automatically invoke the constructor of the base class, you have to call it yourself specifically.

Precede the method call with the class name prefix, and then pass the self variable and other parameters to it.

Note that when we use the Tell method of the Schoolmember class, we take the instance of teacher and student only as an instance of Schoolmember.

Also, in this example, we call the Tell method of the subtype, not the Tell method of the Schoolmember class. It can be understood that Python is always looking for a method of the corresponding type first, in this case. If it cannot find the corresponding method in the export class, it begins to look up one by one in the base class. The base class is specified in the tuple when the class is defined.

A comment for a term--if more than one class is listed in an inheritance tuple, it is called multiple inheritance.


Classes for Python

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.