Python3 面向对象编程

1、面向对象编程的特征

1、封装:对外部隐藏对象的工作细节

2、继承:子类可以继承父类的属性和方法

3、多态:不同类的对象可以调用相同的函数名,但结果不同

>>> "FishC.com".count('o')
1
>>> [1, 1, 2, 3, 5, 8].count(1)
2
>>> (0, 2, 4, 8, 12, 18).count(1)
0

2、self参数的作用

绑定棒法(对象.方法),对象在使用方法是会把对象名传递给self参数,这样python就知道哪个对象在调用方法了

3、不希望对象的属性被外部直接引用的方法(“私有化”)

在属性前加上双下划线,但这种方法仍可以用“_类名__变量名”访问

>>> class Person:
__name = '小甲鱼'
        def getName(self):
                return self.__name

>>> p = Person()
>>> p.__name
Traceback (most recent call last):
  File "<pyshell#56>", line 1, in <module>
    p.__name
AttributeError: 'Person' object has no attribute '__name'
>>> p.getName()#内部访问
'小甲鱼'

4、魔法方法(构造方法)__init__(self)

__init__方法在类被实例化之后会被自动调用,可以重写这个方法为对象指定初始化方案

5、模拟小游戏乌龟吃鱼

import random as ra

class Turtle:
    def __init__(self):
        self.x=ra.randint(1,10)
        self.y=ra.randint(1,10)
        self.spirit=100
    def move(self):
        new_x=self.x+ra.choice([1,2,-1,-2])
        new_y=self.y+ra.choice([1,-1])
        
        if new_x < 0:
            new_x=0-new_x
        elif new_x > 10:
            new_x=10-(new_x-10)
        else:
            self.x = new_x#移动到新的位置

        if new_y < 0:
            new_y=0-new_y
        elif new_y > 10:
            new_y=10-(new_y-10)
        else:
            self.y = new_y#移动到新的位置
        self.spirit -= 1
        return (self.x,self.y)
    def eat(self):
        self.spirit+=20
        if self.spirit>=100:
            self.spirit=100

class Fish:
    def __init__(self):
        self.x=ra.randint(1,10)
        self.y=ra.randint(1,10)
    def move(self):
        new_x=self.x+ra.choice([1,-1])
        new_y=self.y+ra.choice([1,-1])

        if new_x < 0:
            new_x=0-new_x
        elif new_x > 10:
            new_x=10-(new_x-10)
        else:
            self.x = new_x#移动到新的位置

        if new_y < 0:
            new_y=0-new_y
        elif new_y > 10:
            new_y=10-(new_y-10)
        else:
            self.y = new_y#移动到新的位置  
        return (self.x,self.y)
        
fish=[]#鱼缸
t1=Turtle()#产生一直乌龟
for i in range(10):#产生10条鱼
    new_Fish=Fish()
    fish.append(new_Fish)

while True:
  
    if not t1.spirit:
        print('乌龟体力耗尽游戏结束')
        break
    if not len(fish):
        print('鱼被吃完游戏结束')
        break
    pos = t1.move()
    for each_Fish in fish[:]:
        each_Fish.move()
        if each_Fish.move()==pos:
            t1.eat()
            fish.remove(each_Fish)
            print("一条鱼被吃掉了!")

 

posted @ 2018-02-04 17:14  消灭猕猴桃  阅读(241)  评论(0编辑  收藏  举报