Python Object-oriented (i)

Source: Internet
Author: User
Tags class definition function definition

Python has been an object-oriented language since its inception, which is why it is easy to create a class and object in Python. introduction of Object-oriented technology
    • Class: 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.

    • Class variables: Class variables are common throughout the instantiated object. Class variables are defined in the class and outside the body of the function. Class variables are not typically used as instance variables.

    • Data members: Class variables or instance variables are used to manipulate related data for classes and their example objects.

    • Method overrides: If a method inherited from a parent class does not meet the requirements of a subclass, it can be overridden, a procedure called method overrides, also known as a method.

    • Instance variable: A variable defined in a method that acts only on the class of the current instance.

    • Inheritance: A derived class inherits the fields and methods of the base class. Inheritance also allows the object of a derived class to be treated as an object of a base class. For example, there is a design where an object of type dog is derived from the animal class, which is the simulation "is a" relationship (for example, Dog is a animal)

    • Instantiation: Creates an instance of a class, the concrete object of the class.

    • Method: A function defined in a class

    • Object: an instance of a data structure defined by a class. The object consists of two data members (class variables and instance variables) and methods.

Ii. What is Object-oriented program design and why should it

Process-oriented program design is the core of process (pipeline thinking), the process is to solve the problem of the steps, process-oriented design is like a well-designed pipeline, consider when to deal with what things.

The advantages are: greatly reduce the complexity of the program, the complexity of the problem is simplified, the process of

disadvantage is: poor scalability, a set of pipeline or process is to solve a problem , the production line of soda can not produce a car, even if it can, also have to change, change a component, reaching.

Application scenario: Once you have completed a very rarely changed scenario, the notable examples are Linux kernel, git, and Apache HTTP server.

Object-oriented program design is the core of the object (God-like thinking), the object is a combination of characteristics (variables) and skills (functions), to understand what the object is, we must regard themselves as God, God in the eyes of the world exists in all things are objects, not exist can also be created.

In the real World: Object----(common features and skills)---> class

In the program: Define class----(instantiate)-----> objects

Summary:

The advantage is that it solves the extensibility of the program. A single modification of an object is immediately reflected in the entire system, such as the character of a character parameter in the game and the ability to modify it easily.

Cons: Poor controllability

iii. Classes and Objects

3.1 What is an object and what is a class

Everything in Python is an object, and Python unifies the concept of classes and types, which are classes

Class definition

The syntax format is as follows:

1.  Class class name:    #  class name capitalized    ' ' annotation  '     body 2 . class ClassName:         <statement-1> ...     <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

Class objects support two operations: Property Reference 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 this:

classMyclass:"""a simple instance of a class"""I=12345deff (self):return 'Hello World'#Instantiating Classesx=Myclass ()#accessing the properties and methods of a classPrint("the attribute I of the MyClass class is:", X.I)Print("the method F output of the MyClass class is:", X.F ())

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

The output is:

The properties of the MyClass Class I are: Method of the 12345MyClass class F output is: Hello World

Many classes tend to create objects with an initial state. So the class might define a special method (constructor) named __init__ (), like this:

def __init__ (self):        self.data = []    #定义空列表

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

classTeacher:school='Oldboy'    #defining common characteristics of objects    def __init__(self,name,age):#user-created object-passed parametersSelf.name=name Self.age= AgedefTalk (self):Print('is talking')    defWalk (self):Print('is walking') T1=teacher ('Egon', 23)#instantiation: __init__ (T1, ' Egon ', at $)T2=teacher ('Alex', 32)#instantiation: __init__ (T2, ' Alex ', +)
Self represents an instance of a class. Rather than classThere 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.
# Property Reference # Data Properties # print (Teacher.school) # print (teacher.__dict__) # Function Properties # print (teacher.walk) # print (t1.name) # print (T2.talk )

  

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 ()

A class has two functions: property Reference and instantiation

1) attribute reference (class name. Properties)

classStudent:school='Oldboy'    def __init__(self,name,age):#used only for initialization, and must not have a return valueSelf.name=name Self.age= AgedefStudy (self):Print('%s is studying'%self.name) S1=student ('Egon', 84)#Step One: Build the object S1 #步骤二: Initialize s1, S1, ' Egon ', 84 to __init__
__init__ is used only to initialize the function, and must not have a return valuedata Properties, function properties:
Print (Student.school)    #引用类的数据属性    #输出结果: Oldboyprint (student.study)    #引用类的函数属性    #输出结果:< function Student.study at 0x00000149f72b7620>

Modification, deletion, and addition of objects:

#ModifyStudent.school='I love you.'    #Modifying the value of a variable schoolPrint(Student.school)#output: Even the fraternity#DeletedelStudent.school#Remove the value of the school propertyPrint(Student.__dict__)#the class name. __DICT__: A dictionary is found, key is the property name value is the property valueoutput: (above is not deleted, after deletion, through the __dict__ can see the information of the class) {'__module__':'__main__','School':'I love you.','__init__': <function Student.__init__At 0x000001bb20097598>'study': <function student.study at 0x000001bb20097620>'__dict__': <attribute'__dict__'Of'Student'Objects>,'__weakref__': <attribute'__weakref__'Of'Student'Objects>,'__doc__': None} {'__module__':'__main__','__init__': <function Student.__init__At 0x000001bb20097598>'study': <function student.study at 0x000001bb20097620>'__dict__': <attribute'__dict__'Of'Student'Objects>,'__weakref__': <attribute'__weakref__'Of'Student'Objects>,'__doc__': None}#Addstudent.x=6666666666666#Add an attribute x=6666666666666Print(student.x)Print(Student.__dict__)#I can see a value in the dictionary.

As long as the object binding method will pass the dictionary value, pass yourself to the function

S1.study ()   #调用函数 Egon is studying

  

2) Where does the attribute of the class we define exist? There are two ways of viewingdir (class name): A list of names is isolatedthe class name. __DICT__: A dictionary is found, key is a property name, value is a property value 3) Special class propertiesclass name. __name__ # class name (string)the document string for the class name. __doc__ # classclass Name The first parent class of the __base__ # classclass name. __bases__ # class tuple of all parent classesClass Name The dictionary property of the __dict__ # classclass name the module where the __module__ # class is definedclass name. __class__ # classes corresponding to instances (in modern class only) 4) Object/instanceThe object/instance itself has only data properties, but the Python class mechanism binds the function of the class to the object, called the object's method, or is called a binding method, the binding method uniquely binds an object, the method of the same class binds to a different object, and it belongs to a different method. Memory addresses are not the sameThe special thing about object binding methods is that Obj.func () passes obj to the first argument of Func  5) Class namespace and object/instance namespaceCreating a class creates a namespace for a class that stores all the names defined in the class, called Properties of the classclasses have two properties: Data properties and Function Propertieswhere the data properties of a class are shared with all objects, and the function properties of the class are bound to all objects Creating an object/instance creates an object/instance namespace that holds the name of the object/instance , called the object/instance propertyin the obj.name would prefer to find the name in Obj's own namespace, can not find the class to find, the class will not find the parent class, and finally can not find the exception thrownpractice a bunch of classes:
# Teacher Class Teacher:    school= ' Oldboy '    def __init__ (self,name,age):        self.name=name        self.age=age    def Talk:        print (' was talking ')    def Walk (self):        print (' was walking ') t1=teacher (' Egon ', ')   # instantiation: __init__ (T1, ' Egon ', $) t2=teacher (' Alex ', +)   # instantiation: __init__ (T2, ' Alex ', 32)

  

# Student Class Student:    job= ' Student '    def __init__ (self,name,age):        self.name=name        self.age=age    def talk (self):        print ("is Talk")    Def Eat (self):        print (' is    eating ') s1=student (' Buer ') # instantiation: __init__ (S1, ' Buer ', ') s2=student (' Dongbei ', 22) # Instantiation: __init__ (S2, ' Dongbei ', ') print (S1)

  

# Dog Class Dog:    bottle= ' dog '    def __init__ (self,name,color):        self.name=name        self.color=color    Def talk (self):        print (' Bark ')    def Eat (self):        print (' dog good ') d1=dog (' Husky ', ' blank ')   # instantiation: __init__ ( D1, ' Husky ', ' blank ') d2=dog (' Teddy ', ' Brown ')    # instantiation: __init__ (D2, ' Teddy ', ' Brown ')

  

# Pig class Pig:    bottle= ' big '    def __init__ (self,name):        self.name=name def talk (self    ):        Print (' Hum hum ')    Def eat (self):        print (' pig good ') p1=pig (' Xiangzhu ')  # instantiation: __init__ (P1, ' Xiangzhu ') p2=pig (' Huazhu ')    # Instantiation: __init__ (P2, ' Huazhu ') print (p1)

  

# Animal class Animal:    local= ' Zoo '    def __init__ (self,name,kind):        self.name=name        self.kind=kind    Def talk (self):        print (' People does not know-to-say ') def pull ("self")    :        print (' No need for toilet ') a1=animal ( ' Xingxing ', ' monkey ') a2=animal (' Fenda ', ' Panda ')

  

Python Object-oriented (i)

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.