037 Classes and objects: Object-oriented Programming

Source: Internet
Author: User

Object-oriented programming (OOP)
OOA: Object-oriented Analysis
OOD: Object-oriented design
OOP: Object-Oriented Programming

What is 1.self?
Self in Python is equivalent to the this pointer of C + +
Just as a class is a drawing, and the object is a house where people can live, each house grows the same, but they have different owners, self is equivalent to the number of each house.
The function of the self parameter: The binding method, with the self parameter Python can distinguish which object to call the method;
You can think of self as a unique identifier for an instance object.
Cases:
>>> Class Ball:
...: def setName (self,name):
... self.name = name
... def kick (self):
... print (' I am%s '% self.name)
...
>>> a = Ball () # The first argument self tells Python that the A object is in the call method, because it is hidden and passed in by Python itself, so we don't need to write it here.
>>> B = Ball ()
>>> a.setname (' a ')
>>> b.setname (' B ')
>>> A.kick ()
I am A
>>> B.kick ()
I am B

The Magic method of 2.python
It is said that Python's objects are inherently endowed with some magical methods, all of which are object-oriented python ...
They are a special way to add magic to your class.
If your object implements one of these methods, the method will be called by Python in a special case, and this happens automatically.

__init__ (self): The method of construction, the most basic method of magic. When an object is instantiated, it is automatically called when the method is created
__init__ (Self,param1,param2 ...): parameters can be passed in when instantiated.
__init__ method: Can not return any object except None

such as:>>> class ball:
... def __init__ (self,name):
... self.name = name
... def kick (self):
... print (' I am%s '% self.name)
...
>>> b = Ball (' B ')
>>> B.kick ()
I am B

3. Shared and private
The properties and methods in Python are common by default and can be used with '. ' To access
such as:>>> class Person:
... name = ' HaHa '
...
>>> p = person ()
>>> P.name
' HaHa '

Name mangling: Names change, name reorganization, can achieve similar private functions
The name change is the variable "__" changed to "_ Class name __ variable name"

Define private functions or variables: Add "__" to two underscores before a variable or function name
such as:>>> class Person:
... __name = ' HaHa '
...
>>> p = person ()
>>> P.__name
Traceback (most recent):
File "<stdin>", line 1, in <module>
Attributeerror:person instance has no attribute ' __name '
Now __name is a private variable that cannot be accessed externally
If you want to access __name This private variable, you need to access it internally in theory.
such as:>>> class Person:
... __name = ' HaHa '
... def getName (self):
... return Self.__name
...
>>> p = person ()
>>> P.getname ()
' HaHa '
But now you can access it in another way, because the name change is changing the variable that starts with "__" to "_ Class name __ variable name", so
such as:>>> P._person__name
' HaHa '
So Python's private is pseudo-private, and the Python class is unrestricted.


Practice:
1. Write a playground ticket class, calculate two adults a child weekday fares
Weekday fare 100 yuan
Weekends for weekdays of 120%
Kids half Price s
1 #!/usr/bin/python
2 #coding: UTF8
3
4 Class Ticket:
5 def __init__ (Self,week = False,child = False):
6 self.exp = 100
7 If week:
8 Self.inc = 1.2
9 Else:
Ten self.inc = 1
If child:
Self.discount = 0.5
-Else:
Self.discount = 1
def calcprice (Self,num):
Return (SELF.EXP * self.inc * self.discount * num)
17
Adult = Ticket ()
Child = Ticket (child=true)
Print ("2 adults + 1 children on weekdays fares:%.2f"% (Adult.calcprice (2) + child.calcprice (1)))


2. Game programming: Define a turtle and fish according to the following requirements and write a game
The game scene is a range (x, y) of 0<=x<=10,0<=y<=10
Game Spawn 1 turtles and 10 fish
They all move in random directions.
The turtle's maximum mobility is 2 (can randomly choose 1 or 2), the maximum mobile capacity of the fish is 1
Automatically moves in the opposite direction when moving to the edge of the scene
Turtle initialization strength is 100 (upper limit)
Every time a turtle moves, it consumes 1 of its energy.
When the turtle and the fish coordinates overlap, the turtle eats the fish, the turtle physical strength increases 20
Fish do not calculate physical strength
When the turtle physical value is 0 (hanging off) or the number of fish is 0 game over

1 #!/usr/bin/python
2 # Coding:utf8
3
4 Import random as R
5
6 legal_x = [0,10]
7 legal_y = [0,10]
8
9 Class Turtle:
Ten def __init__ (self):
Self.power = #初始化体力
self.x = R.randint (legal_x[0],legal_x[1]) #初始化位置随机
SELF.Y = R.randint (legal_y[0],legal_y[1])
14
def move (self):
new_x = self.x + R.choice ([1,2,-1,-2]) #随机计算方向 and move to the new location (x, y)
new_y = self.y + R.choice ([1,2,-1,-2])
18
If new_x < legal_x[0]: #检查移动后是否超出了场景x轴边界
self.x = legal_x[0]-(new_x-legal_x[0])
Elif new_x > Legal_x[1]:
self.x = legal_x[1]-(new_x-legal_x[1])
+ Else:
self.x = new_x
25
If New_y < legal_y[0]: #检查移动后是否超出了场景y轴边界
SELF.Y = legal_y[0]-(new_y-legal_y[0])
Elif new_y > Legal_y[1]:
SELF.Y = legal_y[1]-(new_y-legal_y[1])
-Else:
SELF.Y = new_y
32
Self.power-= 1 #体力消耗
Return (SELF.X,SELF.Y) #返回移动后新的位置
35
Def eat (self):
PNS Self.power + = 20
If Self.power > 100:
Self.power = 100
40
Class Fish:
def __init__ (self):
self.x = R.randint (legal_x[0],legal_x[1]) #初始化位置随机
SELF.Y = R.randint (legal_y[0],legal_y[1])
45
def move (self):
new_x = self.x + R.choice ([1,-1]) #随机计算方向 and move to the new location (x, y)
new_y = self.y + R.choice ([1,-1])
49
If new_x < legal_x[0]: #检查移动后是否超出了场景x轴边界
Wuyi self.x = legal_x[0]-(new_x-legal_x[0])
Elif new_x > Legal_x[1]:
self.x = legal_x[1]-(new_x-legal_x[1])
Wu Else:
self.x = new_x
56
If New_y < legal_y[0]: #检查移动后是否超出了场景y轴边界
SELF.Y = legal_y[0]-(new_y-legal_y[0])
Elif new_y > Legal_y[1]:
SELF.Y = legal_y[1]-(new_y-legal_y[1])
The Else:
SELF.Y = new_y
63
Return (SELF.X,SELF.Y) #返回移动后新的位置
65
Turtle = Turtle ()
67
Fish = []
A-I in range (10):
New_fish = Fish ()
Fish.append (New_fish)
72
While True:
If not Len (fish):
Print ("The fish is finished, the game is Over")
Break
If not turtle.power:
Print ("Turtle exhaustion")
Break
80
Bayi pos = Turtle.move ()
Each_fish in fish[:]:
If each_fish.move () = = pos:
Turtle.eat () #鱼儿被吃掉了
Fish.remove (Each_fish)
("A fish has been eaten")

037 Classes and objects: Object-oriented Programming

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.