day14-面向对象3

2018-08-02  本文已影响0人  七一欧

01-重写


class Animal(object):
    """动物类"""
    def __init__(self):
        self.age = 0
        self.color = ''

    def eat(self):
        print('吃东西')

    def shout(self):
        print('叫唤')

    @classmethod
    def get_number(cls):
     #  保留父类的类方法的功能的时候,还是super().类方法
        return 100

class Dog(Animal):
    """狗类"""
    def watchdog(self):
        print('看家')

    #  重写父类的shout
    def shout(self):
        print('汪汪汪---!!')
    # 重写父类eat方法
    def eat(self):
        # 保留父类eat功能
        super().eat()
        print('吃骨头')

    @classmethod
    def get_number(cls):
        print(super().get_number())

if __name__ == '__main__':
    dog = Dog()
    dog.age = 3
    dog.eat()

    an  = Animal()
    # 继承后,父类不能使用子类中添加的属性和方法

02-添加属性

# class Person(object):
#     """人类"""
#     def __init__(self,name,age=0):
#         self.name = name
#         self.age = age
#
# class Staff(Person):
#     # init方法中的参数:保证在创建对象的时候就可以给某些属性赋值
#     def __init__(self,name='',age=0,salary=0):
#         super().__init__(name)
#         self.salary = 0
#
# if __name__ == '__main__':
#     s1 = Staff()
#     print(s1.name)
#     s1.salary = 10000
#     print(s1.salary)
class Person(object):
    def __init__(self,name,sex='',age=10):
        self.name = name
        self.age = age
        self.sex = sex
        self.height =0

class Student(Person):
    def __init__(self,name,age=0,tel='00'):
        super().__init__(name,age=age)
        self.stuid = '00'
        self.score = 0
        self.tel = tel

stu1 = Student('李四')
print(stu1.age)

03-运算符的重载

class Student:
    # python不支持方法的重载
    # def run(self):
    #     print('人在跑')

    def run(self,name):
        print('%s在跑'% name)

+、-

class Student2:
    def __init__(self,name='',age=0,height=0):
        self.name = name
        self.age = age
        self.height = height
  self > other
 
  def __gt__(self, other):
      # 比较对象1>对象2的时候是比较他们的height属性
      return self.height > other.height
    def __lt__(self, other):
        return self.age<other.age
    def __add__(self, other):
        return self.age + other.age
    def __sub__(self, other):
        return self.height - other.height
if __name__ == '__main__':
    # stu = Student()
    # stu.run()

    stu1 = Student2('aa',18,height=180)
    stu2 = Student2('bb',10,height=160)
    if stu1 > stu2:
        print('学生1大于学生2')

04-python中的内存管理

引用

class Person:
    def __init__(self,name):
        self.name = name
    def run(self):
        print('人在跑')


if __name__ == '__main__':
    # 声明了一个Person对象,存到p中的
    p = Person('')
    p.run()
    # 删除对象的唯一的引用,对象就会被销毁
    del p
    # p.run()

    # Person对象(0),name='p1'  0+1+1-1-1
    p1 =Person('xzq')
    p2 = p1
    del p2
    p1.run()
    p1 = 'a'

    # 注意:将对象添加到容器中,对象的引用会+1
    p3 = Person('p3')
    lists = [p3]
    del p3

05-包的使用

上一篇下一篇

猜你喜欢

热点阅读