Pyhton精讲day13--Python面向对象基础编程2

继承的概念:子类 自动拥有(继承) 父类 的所有 方法 和 属性 继承的语法

class 类名(父类名):
    pass
  • 子类继承自 父类,可以直接享受 父类中已经封装好的方法,不需要再次开发
  • 子类中应该根据需求,封装子类特有的 属性和方法
  • 当父类的方法实现不能满足子类需求时,可以对方法进行 重写(override)
class Person(object):
    """父类"""
    def __init__(self, id, name=None):
        self.id = id
        self.name = name
    def printInfo(self):
        print(f'编号: {self.id}  姓名: {self.name}')
# 子类继承父类
class Student(Person):
    pass
# 子类继承父类
class Teacher(Person):
    pass
s1 = Student(111, "eric")
s1.printInfo()

父类和子类是一个相对概念

  • 继承的好吹
    不使用继承构造的Circle类和Rectangle类
import math
class Circle(object):
    def __init__(self, color, r):
        self.r = r
        self.color = color
    def area(self):
        return math.pi * self.r * self.r
    def show_color(self):
        print(self.color)
class Rectangle(object):
    def __init__(self, color, a, b):
        self.color = color
        self.a, self.b = a, b
    def area(self):
        return self.a * self.b
    def show_color(self):
        print(self.color)

circle = Circle('red', 3.0)
print(circle.area())
circle.show_color()
rectangle = Rectangle('blue', 2.0, 3.0)
print(rectangle.area())
rectangle.show_color()
  • 重构鲁班打大龙
from random import randint
class Sprite():
    def __init__(self, name, blood, strength):
        self.name = name
        self.blood = blood
        self.strength = strength

    def take_damage(self, sprite):
        if isinstance(sprite, Hero):
            print("Hero 类")
        elif isinstance(sprite, Montser):
            print("Montser 类")
        damage = randint(sprite.strength - 5, sprite.strength + 5)
        self.blood -= damage
        print(f'{self.name} 你被 {sprite.name}攻击, 受到了{damage}点伤害!, 还剩{self.blood}滴血..')
        if self.blood <= 0:
            print(f'{self.name} 你被 {sprite.name}杀死了; 胜败乃兵家常事, 请重新来过!')
            return True
        else:
            return False
class Hero(Sprite):
    def __init__(self, name, blood, strength, skin = None):
        super().__init__(name, blood, strength)
        self.skin = skin

class Montser(Sprite):
    pass
if __name__ == '__main__':
    h1 = Hero("鲁班", 1000, 300)
    m1 = Montser("大龙", 5000, 50)
    while True:
        is_moster_died = m1.take_damage(h1)
        if is_moster_died:
            break
        is_hero_died = h1.take_damage(m1)
        if is_hero_died:
            break

类属性 类方法 静态方法
类对象:类名 实例对象:类创建的对象
类属性就是类对象所拥有的属性,它被所有类对象的实例对象所共有,在内存中只存在一个副本(只被初始化一次),这个和C++、Java中类的静态成员变量有点类似。对于公有的类属性,在类外可以通过类对象(类名)和实例对象访问

class People(object):
    nick_name = "Tom"  #公有的类属性
    __age = 19  #私有的类属性
    id = 0
    def __init__(self, name):
        self.name = name
        self.score = 0
        self.score += 1
        People.id += 1

p1 = People("张三")
p2 = People("李四")
print(p1.nick_name) # 实例对象访问类属性(不建议)
print(People.nick_name) # 类名访问类属性(建议)
print(People.id) # 2
print(p1.score) # 1
print(p2.score) #1
  • 类方法
    类对象所拥有的方法,需要用装饰器@classmethod来标识其为类方法,对于类方法,第一个参数必须是类对象,一般以cls作为第一个参数(当然可以用其他名称的变量作为其第一个参数,但是大部分人都习惯以’cls’作为第一个参数的名字),能够通过实例对象和类对象去访问。
class People(object):
    nick_name = "Tom"  #公有的类属性
    __age = 19  #私有的类属性
    id = 0
    country = "china"
    def __init__(self, name):
        self.name = name
        self.score = 0
        self.score += 1
        People.id += 1
    @classmethod
    def get_country(cls):
        return cls.country
    # 类方法一个用途就是可以对类属性进行修改:
    @classmethod
    def set_country(cls, country):
        cls.country = country
    def hello(self):
        print("hello")
People.set_country('us')
print(People.get_country())
# print(People.hello()) 错误
  • 静态方法
    需要通过修饰器@staticmethod来进行修饰,静态方法不需要定义参数

class People(object):
    nick_name = "Tom"  #公有的类属性
    __age = 19  #私有的类属性
    id = 0
    country = "china"
    def __init__(self, name):
        self.name = name
        self.score = 0
        self.score += 1
        People.id += 1
    # @classmethod
    # def get_country(cls):
    #     return cls.country
    # 错误 不需要参数
    # @staticmethod
    # def get_country(cls):
    #     return cls.country

    @staticmethod
    def get_country():
        return People.country
    # 类方法一个用途就是可以对类属性进行修改:
    @classmethod
    def set_country(cls, country):
        cls.country = country
    def hello(self):
        print("hello")
People.set_country('us')
print(People.get_country())
# print(People.hello()) 错误

因为python中的列表不能完全代替数学中的向量运算, 我们自己实现一个线性代数的向量类

class Vector(object):
    def __init__(self, lst):
        self.__value = lst

    def __str__(self):
        # s = "("
        # for i in range(len(self.__value)):
        #    if i== len(self.__value)-1:
        #        s += str(self.__value[i]) + ")"
        #    else:
        #        s += str(self.__value[i]) + ", "
        # return "({})".format(", ".join([str(i) for i in self.__value]))
        return f'({", ".join([str(i) for i in self.__value])})'

if __name__ == '__main__':
    v1=  Vector([i for i in range(1, 6)])
    print(v1) # (1, 2, 3, 4, 5)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值