Python's initial object-oriented (3--5)

Source: Internet
Author: User
Tags class definition

Process-oriented VS object-oriented:

Process-oriented advantages and disadvantages:

The advantage is that it greatly reduces the complexity of the writing process and only requires

Along the steps to be performed, stack the code.

The disadvantage is: a set of pipeline or process is to solve a problem, code reaching .

Object-oriented advantages and disadvantages:

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, inability to process-oriented programming pipelining can accurately predict the problem of the processing process and results, the object-oriented program once started by the interaction between the object to solve the problem, even God can not predict the end result. So we often see a game of people changes in a certain parameter is likely to lead to the ability of the bully to appear, a knife to kill 3 people, the game is out of balance.

a class has two functions: Property Reference and instantiation Property Reference (class name. Properties)
classPerson:#Define a humanRole =' Person'  #People's role attributes are people    defWalk (self):#people can walk, that is, there is a way to walk        Print("Person is walking ...")Print(Person.role)#View the Role property of a personPrint(Person.walk)#referring to the way people walk, note that this is not the call
Instantiation: The class name parentheses are instantiated, automatically triggering the run of the __INIT__ function, which can be used to customize each instance of its own characteristics
classPerson:#Define a humanRole =' Person'  #People's role attributes are people    def __init__(self,name): Self.name= Name#each character has its own nickname;            defWalk (self):#people can walk, that is, there is a way to walk        Print("Person is walking ...")Print(Person.role)#View the Role property of a personPrint(Person.walk)#referring to the way people walk, note that this is not the call

The process of instantiating is a class-to-object procedure

Originally we had only one person class, in this process, produced an egg object, has its own specific name, attack and health value.

Syntax: Object name = class Name (parameter)

Egg = person (' Egon ')  #类名 () is equal to the execution of person.__init__ () #执行完__init__ () will return an object. This object is similar to a dictionary and has some properties and methods that belong to the person itself. #你可以偷偷的理解: Egg = {' name ': ' Egon ', ' Walk ': Walk}
Viewing Properties & Calling Methods
Print (egg.name)     # View Property Direct object name. Property name Print (Egg.walk ())   # call method, object name. Method Name ()
Supplement to class attributes
A: Where do the properties of the class we define are stored? There are two ways to view Dir (class name): A Name list class name is detected.__dict__: A dictionary is found, key is the property name, value is the attribute two: Special Class attribute class name.__name__#the name of the class (string)The class name.__doc__#the document string for the classThe class name.__base__#the first parent class of a class (speaking of inheritance)The class name.__bases__#a tuple of all the parent classes of the class (speaking of inheritance)The class name.__dict__#Dictionary property of Class!!! The class name.__module__#module where the class definition residesThe class name.__class__#class for instance (in modern class only)

To interpret a class with a function:

defPerson (*args,**Kwargs): self= {}    defAttack (Self,dog): dog['Life_value']-= self['aggressivity']    def __init__(name,aggressivity,life_value): self['name'] =name self['aggressivity'] =aggressivity self['Life_value'] =Life_value self['Attack'] =Attack__init__(*args,**Kwargs)returnSelfegg= Person ('Egon', 78,10)Print(egg['name'])
interpreting classes with functions

Object-oriented summary-The fixed mode of definition and invocation:

classclass Name:def __init__(self, parameter 1, parameter 2): Self. Property of Object 1=parameter 1 self. Properties of the Object 2=Parameter 2defMethod Name (self):Pass    defMethod Name 2 (self):PassObject Name= Class Name ($)#An object is an instance that represents a specific thing.                  #class name (): Class name + parenthesis is the instantiation of a class, equivalent to calling the __init__ method                  #Arguments in parentheses, parameters do not need to pass self, others correspond to parameter one by one in Init                  #The result returns an objectObject name. object's Properties 1#View the properties of an object, directly using the object name. Property nameThe name of the object. Method Name ()#call a method in the class, directly with the object name. Method Name ()
object-oriented fixed mode

Use object-oriented to represent the area and perimeter of a circle:

 fromMathImportPiclassCircle:" "defines a circular class; Provides methods for calculating area and perimeter (perimeter)" " fromMathImportPiclassCircle:def __init__(self,r): SELF.R=RdefArea (self):returnPi*self.r**2defGirth (self):return2*pi*SELF.RR=circle (3)#Instantiate a circlePrint(R.area ())#Print Circle AreaPrint(R.girth ())#print the perimeter of a circle
area and perimeter of a circle
#man dog Wars:#class Person:#def __init__ (self,name,sex,hp,agger):#Self.name=name#Self.sex=sex#self.hp=hp#Self.agger=agger#def hit (Self,dog):#print ('%s hit%s '% (self.name,dog.name))#Dog.hp-=self.agger#class Dog:#def __init__ (self,name,kind,hp,agger):#Self.name=name#Self.kind=kind#self.hp=hp#Self.agger=agger#def Bite (Self,person):#print ('%s bit%s '% (self.name,person.name))#Person.hp-=self.agger#hei = Dog (' Little black ', ' Teddy ', 260,10000)#Obj=person (' Yimi ', ' Girl ', 10,500)#Obj.hit (HEI)#hei.bite (obj)
Man dog War game

Python's initial object-oriented (3--5)

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.