Python Class Learning Notes

Source: Internet
Author: User
Tags class definition function definition inheritance in python

Introduction of object-oriented technology

Class: A collection that describes objects that have the same properties and methods. It defines the properties and methods that are common to each object in the collection. An object is an instance of a class.
Class variables: Class variables are common to the entire instantiated object. The class variable is defined in the class and outside the function body. Class variables are usually not used as instance variables.
Data member: A class variable or instance variable is used to work with related data for a class and its instance objects.
Method Overload: If a method inherited from a parent class does not meet the needs of a subclass, it can be overwritten, which is called the override of the method (override), also known as the overload of the method.
Instance variable: A variable defined in a method that acts only on the class of the current instance.
Inheritance: That is, a derived class (derived class) inherits the fields and methods of the base class (base class). Inheritance also allows the object of a derived class to be treated as a base class object. For example, there is a design where an object of a dog type derives from the animal class, which simulates "is a (is-a)" relationship (an example diagram, dog is a animal).
Instantiating: Creating an instance of a class, a concrete object of a class.
Method: A function defined in a class.
Object: an instance of a data structure defined by a class. An object consists of two data members (class and instance variables) and methods.

Second, create a class
use the class statement to create a new class, followed by the name of the class and ending with a colon, as follows:

The code is as follows Copy Code

Class MyClass:
"" ' A Simple Example Class ' "" Class document string
i = 12345 class variables
def f (self):
Return to ' Hello World '

MYCLASS.I and MYCLASS.F are valid property references that return an integer and a method object, and can also assign a value to a class property, you can modify it by assigning a value to Myclass.i, __doc__ is also a valid property, the returned document string: "A simple Example Class "

The above creates a new class instance and assigns the object to the local variable x.

This instantiation operation ("Invoke" a class object) creates an empty object. Many classes tend to create objects that have an initial state. The class may therefore define a special method named __init__ (), as follows:

The code is as follows Copy Code


def __init__ (self):

Self.data = []

class defines the __init__ () method, the instantiated operation of the class automatically calls the __init__ () method for the newly created class instance. So in the following example, you can create a new instance like this:

The code is as follows Copy Code

x = MyClass ()

Of course, the __init__ () method can have parameters. In fact, parameters are passed through __init__ () to the instantiation of the class. For example:

The code is as follows Copy Code
>>> class Complex:
... def __init__ (Self,realpart,imagpart):
... self.r = Realpart
... self.i = Imagpart
...
>>> x = Complex (3.0,-4.5)
>>> X.R, x.i
(3.0,-4.5)

Instance Object

Now, what can we do with instance objects? The operation of an instance object has only a property reference. There are two valid property names, data properties, and methods.

The Data property corresponds to the Smalltalk in C or the data member in C + +. As with local variables, data attributes do not need to be declared, and the first use is declared. For example, if X is the MyClass instance that was previously created, the following code will print a value of 16 without any extra:

The code is as follows Copy Code


X.counter = 1
While X.counter < 10:
X.counter = X.counter * 2
Print X.counter
Del X.counter

The second reference property that is accepted for an instance object is a method. Method is a function that belongs to an object. (in Python, methods are not unique to class instances: Other types of objects can also have methods.) For example, a list object has Append,insert,remove,sort and so on. However, here, unless specifically stated, the method we refer to refers specifically to the class method)

The valid name of an instance object depends on its class. By definition, all (user-defined) function objects in a class correspond to the methods in its instance. So in our case, X.. F is a valid method reference, because MYCLASS.F is a function. But x.i is not because myclass.i is not a function. But X.f and MYCLASS.F are different--it's a method object, not a function object.


Method Object

method is usually called directly.

X.F ()

In the case of MyClass, this will return the string ' Hello World. ' However, there is no need to call the method directly. XF is a method object that can be stored up for later invocation. For example:

The code is as follows Copy Code


XF = X.F
While True:
Print XF () #会不断www. 111cn.net Printing "Hello World".

What exactly happens when a method is invoked? You may have noticed that when you call X.F (), you do not elicit the previously marked variable, although you specify a parameter in the definition of the F () function. What's wrong with this argument? If the parameter is missing from the function call, Python throws an exception--even if it doesn't actually work ...

In fact, you may have guessed the answer: the special part of the method is that the instance object is passed to the function as the first parameter of the function. In our example, the call to X.F () is the equivalent of MYCLASS.F (x). In general, calling a method with a list of n arguments is equivalent to inserting the object of the method into the front of the argument list, and calling the corresponding function in the list.

In practice, the first parameter of a method is named self. This is just a convention: For Python, Self has absolutely no special meaning. (note, however, that if you do not comply with this convention, other Python programmers will have trouble reading your code, and some class browsing programs are also developed by following this Convention.) )

Any function object in a class property is defined as a method in the class instance. You do not have to write the function definition code into the class definition, or you can assign a function object to a variable in the class. For example:

The code is as follows Copy Code
# Function defined outside the class
Def f1 (self, x, y):
return min (x, x+y)

Class C:
F = F1
def g (self):
Return to ' Hello World '
h = g

Now F, G and H are all properties of Class C, all referenced are function objects, so they are all C instance methods--h strictly equal to G. It should be noted that this habit usually only confuses the reader of the program.

By using the method property of the self parameter, the method can invoke another method:

The code is as follows Copy Code


Class Bag:
def __init__ (self):
Self.data = []
def add (self, x):
Self.data.append (x)
def addtwice (self, x):
Self.add (x)
Self.add (x)

Python Built-in class properties

__DICT__: The properties of the class (including a dictionary, consisting of the data properties of the Class)
__DOC__: Document string for Class
__NAME__: Class name
__MODULE__: The module in which the class definition resides (the full name of the class is ' __main__.classname ', and if the class is in an import module mymod, then classname.__module__ equals www.111cn.net mymod)
__bases__: All the parent classes of a class constitute elements (including a tuple of all parent classes)

The Python built-in class property invocation instance is as follows:

The code is as follows Copy Code


#!/usr/bin/python
Class Employee:
' Common base class for all employees '
Empcount = 0

def __init__ (self, Name, salary):
Self.name = Name
Self.salary = Salary
Employee.empcount + 1

def displaycount (self):
Print "Total Employee%d"% Employee.empcount

def displayemployee (self):
Print "Name:", Self.name, ", Salary:", self.salary
Print "employee.__doc__:", employee.__doc__
Print "employee.__name__:", employee.__name__
Print "employee.__module__:", employee.__module__
Print "employee.__bases__:", employee.__bases__
Print "employee.__dict__:", employee.__dict__

The result of executing the above code output is as follows:


EMPLOYEE.__DOC__: Common base class for all employees
EMPLOYEE.__NAME__: Employee
EMPLOYEE.__MODULE__: __main__
Employee.__bases__: ()
employee.__dict__: {' __module__ ': ' __main__ ', ' displaycount ':
<function Displaycount at 0xb7c84994>, ' Empcount ': 2,
' Displayemployee ': <function displayemployee at 0xb7c8441c>
' __doc__ ': ' Common base class for all employees ',
' __init__ ': <function __init__ at 0xb7c846bc>}

Iii. Inheritance of Classes

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

What to note: Inheritance syntax class derived class name (base class name)://... base class name writing parentheses, the base class is specified in the tuple when the class is defined.

Some of the features of inheritance in Python:


1: The construction of the base class (__init__ () method) in inheritance is not invoked automatically, and it needs to be specifically invoked in the construction of its derived class.
2: When calling a method of a base class, you need to prefix the class name of the base class with the Self argument variable. Unlike calling a normal function in a class, you do not need to take the self argument
3:python always first finds a method of the corresponding type, and if it cannot find the corresponding method in the derived class, it begins to look in the base class individually. (Find the Called method first in this class and find it in the base class.)

If more than one class is listed in the inheritance tuple, it is called "Multiple inheritance."

Grammar:

The declaration of a derived class, similar to their parent class, is followed by a list of inherited base classes following the class name, as follows:

The code is as follows Copy Code


Class Subclassname (parentclass1[, ParentClass2, ...]):
' Optional class documentation string '
Class_suite

Example:

The code is as follows Copy Code


#!/usr/bin/env python
#coding: UTF8
Class Parent: # define Parent class
parentattr = 100
def __init__ (self):
Print "Calling parent constructor"

def parentmethod (self):
print ' Calling parent method '

def setattr (self, attr):
Parent.parentattr = attr

def getAttr (self):
print "Parent attribute:", parent.parentattr

Class Child (Parent): # define Child class
def __init__ (self):
Print "Calling child constructor"

def childmethod (self):
print ' calling child method '

c = Child () # Instantiate a subclass
C.childmethod () # calls a subclass's method
C.parentmethod () # Calling the parent class method
C.setattr (200) # The method of calling the parent class again
C.getattr () # The method of calling the parent class again

The above code execution results are as follows:


Calling Child constructor
Calling child method
Calling parent method
Parent attribute:200

Overloaded methods

If the functionality of your parent's method does not meet your needs, you can overload the parent class's methods in the subclass:

Instance:

  code is as follows copy code

#!/usr/bin /python
 
Class parent:        # defines the parent class
   def myMethod ( Self):
      print ' Calling parent method '
 
Class Child (Parent): # define subclasses
&N bsp;  def myMethod (self):
      print ' calling child method '
 ,
C = Child ()           # Subclass Instance
C.mymethod ()           # Subclass calls overloaded methods

Executes the above code output as follows:


Calling child methods

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.