python面向对象学习

面向对象最重要的概念就是类(Class)和实例(Instance),必须牢记类是抽象的模板,比如Student类,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同。

面向对象三个概念:
1.封装
即把客观事物封装成抽象的类,并且类可以把自己的数据和方法让可信的类进行操作,对不可信的进行隐藏

class Cat(Animal):
    def bite(self):
        print("猫咪咬")

lanmao = Cat()

2.继承
一个类可以继承其他一个类的属性和方法,比如我们定义一个动物类和猫咪类,猫咪继承动物,这样实例化一个猫咪对象时,猫咪也继承了动物类的跑方法
如果需要继承

class Animal:
    def run(self):
        print("跑得快")

class Cat(Animal):
    def bite(self):
        print("猫咪咬")

lanmao = Cat()
lanmao.run()

>>跑得快

使用继承时,通常会用到super()方法,在python2中,通常需要在super()中加上Object,python3不需要添加,可以使用super()提高代码的可复用性、可维护性
以下函数,Cat类继承Animal中的初始化中的方法

class Animal:
    def __init__(self,life):
        self.life = life
        print(self.life)

class Cat(Animal):
    def __init__(self,life):
        super().__init__(life)
        self.life = life
a = Animal(223)
mimi = Cat(45)

>>223
45

3.多态
看如下代码,当子类和父类都存在相同的run()方法时,我们说,子类的run()覆盖了父类的run(),在代码运行的时候,总是会调用子类的run()。这样,我们就获得了继承的另一个好处:多态。在子类调用run方法时,无论子类怎样调用,都不会影响到其他子类继承父类的方法去调用使用

class Animal:
    def run(self):
        print("跑得快")

class Cat(Animal):
    def bite(self):
        print("猫咪咬")
    def run(self):
        print("猫咪在跑")
class Dog(Animal):
    def laugh(self):
        print("小狗在笑")

lanmao = Cat()
wangcai = Dog()
lanmao.run()
wangcai.run()

>>猫咪在跑
跑得快

在业务编写时,需要发掘重要的业务领域概念,建立业务领域概念之间的关系,找名词,加属性,连关系
其中对象之间的还有各种依存关系,限于篇幅和笔者个人能力不一一赘述

class Role(object):
    def __init__(self,name,role,weapon,attack,life_value = 100,money = 10000):
        self.name = name
        self.role =role
        self.weapon = weapon
        self.life_value = life_value
        self.money = money
        self.attack = attack
    def shot(self,other):
        print('%s 在射击' %self.name)
        print('%s跟%s在中路拼枪' %(self.name,other.name))
        self.life_value = int(self.life_value)-int(other.attack)
        if self.life_value > 0:
            print('%s活下来了,还剩下%s血'%(self.name,self.life_value))
        else:
            print('%s挂了,充点钱吧,充钱才能更强'%self.name)
    def get_shot(self,attract):
        # self.life_value -= int(attract)
        print('%s 被射中了,还剩下%s 血' %(self.name,self.life_value))

    def arm(self,gun):
        self.attack =int(self.attack)+int(gun.attack)
        self.weapon = gun.name
        self.money =int(self.money)-int(gun.money)
        print('%s %s 装备了%s,攻击力提升啦,竟然达到了惊人的%s 点' %(self.role,self.name,
                                                  self.weapon,self.attack))
        print('%s 买了%s,还剩下 %s元钱' %(self.name,gun.name,self.money))

class Gun(object):
    def __init__(self,name,attack,money):
        self.name=name
        self.attack = attack
        self.money = money
ak47 = Gun('AK47','89','3000')
an94 = Gun('AN94','90','5000')
lsj  = Role('lsj','police','knief',10)
wyz  = Role('wyz','bandit','knief',10)

lsj.arm(ak47)
wyz.arm(an94)
lsj.shot(wyz)
wyz.shot(lsj)
上一篇:练习1 _ 类和对象


下一篇:英语听力-第一课