Python3 Object-oriented

Source: Internet
Author: User
Tags class definition

Introduction to Object-oriented technology
    • Class (Class):   is used to describe a collection of 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.
    • method: A function defined in the class.
    • data members: class variables or instance variables are used to manipulate the data related to the class and its instance objects.
    • method Overrides: If a method inherited from a parent class does not meet the requirements of the subclass, it can be overridden, which is called the override of the method and is also an override of the method.
    • instance variable: A variable defined in a method that acts only on the class of the current instance.
    • inheritance: a derived class (derived class) that inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as a base class. GCA, there is a design: A dog-type object derives from the animal class, which is the simulation "is a (is-a)" Relationship (example, dog is a animal).
    • instantiation: Creates an instantiation of a class, the concrete object of the class.

In contrast to other programming languages, Python joins the class mechanism without adding new syntax and semantics.

The classes in Python provide all the basic functions of object-oriented programming: The inheritance mechanism of classes allows for multiple base classes, and derived classes can overwrite any method in the base class, and the method can be called in the base class with the same name.

An object can contain any number and type of data.

class definition

The syntax format is as follows:

1 class   ClassName:2     <statement-1>3     . 4      . 5      . 6     <statement-N>

After a class is instantiated, its properties can be used, and in fact, after a class is created, its properties can be accessed through the class name.

Class object

The class object supports two operations: property application and instantiation.

The property reference uses the same standard syntax as all property references in Python: Obj.name.

After a class object is created, all the names in the class namespace are valid property names, so if the class definition is:

1 classMyClass ():2     "A simple example of a person"3i = 1234564     deff (self):5         return 'Hello World'6  #instantiation of7X =MyClass ()8 9 #accessing the properties and methods of a classTen Print("the attribute I of the MyClass class is", X.I) One  A Print("MyClass L class method F output is", X.F ())

The above creates a new class instance and pays the object to the local variable x,x to an empty object.

Execute the above program output as:

The properties of the MyClass Class I are: 12345
 The method output for the MyClass class is: Hello   World

Class has a special method called __init__ (), which is called automatically when the class is instantiated, as follows:

def __init__ (self):     = []

class defines the __init__ () method, and the instantiation operation of the class automatically calls the __init__ () method. The corresponding __init__ () method is called when the class MyClass is instantiated as follows:

x = MyClass ()

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

class Comlex ():     def __init__ (Self,realpart,imagpart):         = Realpart
== Complex (3.0,-4.5)print(x.r,x.i) # output: 3.0-4.5

Self represents an instance, not a class

There is only one special difference between a method of a class and a normal function-----they must have an extra first parameter name, according to the Convention its name is self.

class Test:     def prt (self):         Print (self)         Print (self.) __class__  = Test () t.prt ()

As can be seen from the execution results, self represents an instance of the class, representing the address of the current object, while Self.class points to the class.

Self is not a pyton keyword, and we can change it to Runoob as well:

class Test:     def prt (runoob):         Print (Runoob)         Print (Runoob. __class__  = Test () t.prt ()

The result of the above instance execution is:

<__main__. Test instance at 0x100771878>__main__. Test
Methods of the class

Inside the class, you define a method using the DEF keyword, which differs from the general function definition in that the class method must contain the parameter self, which is the first argument, and self represents an instance of the class.

#class definitionclasspeople:#Defining basic PropertiesName ="' Age=0#define private properties, private properties cannot be accessed directly outside the class    __weight=0#Defining construction Methods    def __init__(self,n,a,w): Self.name=N self.age=a self.__weight=WdefSpeak (self):Print("%s said: I am%d years old. "%(self.name,self.age))#Instantiating Classesp = People ('Runoob', 10,30) P.speak ()

Execute the above program output as:

Runoob said: I am 10 years old.
Inherited

Python also supports the inheritance of classes, and if a language does not support inheritance, the class has little meaning. The definition of a derived class is as follows:

class Derivedclassname (BaseClassName1):         <statement-1> ...     <statement-N>

Note the order of the base class in parentheses, if the same method name is in the base class, and if the subclass is used as specified, the Python left-to-right search means that the method is not found in the subclass, from left to right, to find out if the method is contained in the base class.

Baseclassname (the base class name in the example) must be defined in one scope with the derived class, and can also be useful in expressions where the base class is defined in another module:

class Derivedclassname (ModName. Baseclassname):
#class definitionclasspeople ():#Defining basic PropertiesName =' ' Age=0#define private properties, private properties cannot be accessed directly outside the class    __weight=0#Defining construction Methods    def __init__(self,n,a,w): Self.name=N self.age=a self.__weight=WdefSpeak (self):Print("%s said: I am%d years old. "%(self.name,self.age))#single-Instance inheritanceclassStudent (people): Grade=' '     def __init__(self,n,a,w,g):#calling a method of the parent classPeople.__init__(self,n,a,w,) Self.grade=g#methods to overwrite the parent class    defSpeak (self):Print("%s says: I'm%d years old, I'm reading grade%d."%(Self.name,self.age,self.grade)) s= Student ('JS', 10,60,5) S.speak ()

Execute the above program output as:

JS said: I am 10 years old, I am in the 5 grade
Multiple inheritance

Python also has limited support for multiple inheritance forms. The class definition for multiple inheritance is as follows:

class derivedclassname (Base1, Base2, Base3):         <statement-1> ...     <statement-N>

You need to be aware of the order of the parent class in parentheses, if the same method name is in the parent class and is not specified when the subclass is used, Python

Left-to-right search when a method is found in a subclass, queries from left to right include methods in the parent class.

#class definitionclasspeople ():#Defining basic PropertiesName =' ' Age=0#define private properties, private properties cannot be accessed directly outside the class    __weight=0#Defining construction Methods    def __init__(self,n,a,w): Self.name=N self.age=a self.weight=WdefSpeak (self):Print("%s said: I am%d years old. "%(self.name,self.age))#single-inheritance exampleclassStudent (people): Grade="'    def __init__(self,n,a,w,g):#calling the constructor of the parent classPeople.__init__(self,n,a,w) Self.grade=g#methods to overwrite the parent class    defSpeak (self):Print("%s says: I'm%d years old, I'm reading grade%d."%(Self.name,self.age,self.grade))#another class, the preparation before multiple inheritanceclassspeaker (): Topic="'name="'    def __init__(self,n,t): Self.name=N self.topic=TdefSpeak (self):Print("My name is%s, I am an orator, and the subject of my speech is%s"%(self.name,self.topic))#Multiple Inheritanceclasssample (Speaker,student): a=' '    def __init__(self,n,a,w,g,t): Student.__init__(self,n,a,w,g) speaker.__init__(self,n,t) test= Sample ("Tim", 23,90,5,"python") Test.speak () # method name is the same as, the default call is in parentheses before the parent class method

Execute the above program output as:

My name is Tim, I'm an orator, and the subject of my speech is python.
Method overrides

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

classParent:#defining the Parent class   defMyMethod (self):Print('calling the parent class method') classChild (Parent):#Defining subclasses   defMyMethod (self):Print('Calling Subclass Methods') C= Child ()#sub-class instancesC.mymethod ()#Subclass Call override MethodSuper (CHILD,C). MyMethod ()#calling a method that the parent class has been overridden with a subclass object

The super () function is a method for calling the parent class (the superclass).

Execute the above program output as:

Call the subclass method to call the parent class method
The proprietary methods of the class:
    • __init__: constructor, called when generating an object
    • __del__: destructors, using when releasing objects
    • __repr__: printing, converting
    • __setitem__: assigning values by index
    • __getitem__: getting values by index
    • __len__: Get length
    • __cmp__: comparison operation
    • __call__: function call
    • __add__: add operation
    • __sub__: minus operation
    • __mul__: multiply operation
    • __div__: except operations
    • __mod__: finding the remainder operation
    • __pow__: exponentiation

Python3 Object-oriented

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.