1, object-oriented programming features
1. Encapsulation: Working details of external hidden objects
2. Inheritance: Subclasses can inherit properties and methods of parent class
3, polymorphic: Non-homogeneous objects can call the same function name, but the results are different
" fishc.com ". Count ('o')1>>> [1, 1, 2, 3, 5, 8].count (1)2>> > (0, 2, 4, 8,.). Count (1) 0
2. Function of self parameter
Binding Bar Method (object. method), the object is used by passing the object name to the self parameter, so that Python knows which object is calling the method.
3. Methods that do not want the properties of an object to be directly referenced externally ("privatization")
Precede the attribute with a double underscore, but this method can still be accessed using the _ Class name __ variable name
>>>classPerson :__name='Little Turtle' defGetName (self):returnSelf.__name>>> p =Person ()>>> p.__nameTraceback (most recent): File"<pyshell#56>", Line 1,inch<module>p.__nameAttributeerror:' Person'object has no attribute'__name'>>>p.getname () #内部访问'Little Turtle'
4. Magic method (Construction method) __init__ (self)
The __init__ method is called automatically after the class is instantiated, and you can override this method to specify the initialization scheme for the object.
5. Simulation Game Turtle eats fish
ImportRandom as RaclassTurtle:def __init__(self): self.x=ra.randint (1,10) Self.y=ra.randint (1,10) Self.spirit=100defMove (self): new_x=self.x+ra.choice ([1,2,-1,-2]) new_y=self.y+ra.choice ([1,-1]) ifnew_x <0:new_x=0-new_xelifnew_x > 10: new_x=10-(new_x-10) Else: self.x= new_x#move to a new location ifNew_y <0:new_y=0-new_yelifNew_y > 10: New_y=10-(new_y-10) Else: Self.y= New_y#move to a new locationSelf.spirit-= 1return(SELF.X,SELF.Y)defEat (self): Self.spirit+=20ifself.spirit>=100: Self.spirit=100classFish:def __init__(self): self.x=ra.randint (1,10) Self.y=ra.randint (1,10) defMove (self): new_x=self.x+ra.choice ([1,-1]) new_y=self.y+ra.choice ([1,-1]) ifnew_x <0:new_x=0-new_xelifnew_x > 10: new_x=10-(new_x-10) Else: self.x= new_x#move to a new location ifNew_y <0:new_y=0-new_yelifNew_y > 10: New_y=10-(new_y-10) Else: Self.y= New_y#move to a new location return(SELF.X,SELF.Y) Fish=[]#AquariumT1=turtle ()#The turtle has been produced forIinchRange (10):#Produce 10 fishNew_fish=Fish () fish.append (new_fish) whileTrue:if notT1.spirit:Print('Turtle physical exhaustion Game over') Break if notlen (fish):Print('The fish is finished eating the game') BreakPOS=T1.move () forEach_fishinchfish[:]: Each_fish.move ()ifEach_fish.move () = =pos:t1.eat () fish.remove (each_fish)Print("A fish has been eaten! ")
Python3 Object-Oriented programming