面向对象

文章目录

封装

封装、继承、多态

class Book:
    def __init__(self,title,price=0.0,author=None):
        self.title = title
        self.price = price
        self.author = author

    def print_info(self):
        print(self.title,self.price,self.author)

if __name__ == "__main__":
    book = Book("python经典",price=39.0,author="tom")
    book.print_info()

结果是:
python经典 39.0 tom

class Book:
    def __init__(self,title,price=0.0,author=None):
        self.title = title
        self.price = price
        self.author = author

    def print_info(self):
        print(self.title,self.price,self.author)

    def __repr__(self):
        return"<图书:{}>".format(self.title)
class Book:
    count = 0

    #初始化执行
    def __init__(self,title,price=0.0,author=None):
        self.title = title
        self.price = price
        self.author = author
        Book.count +=1
        
    def __del__(self):
        Book.count -=1

    def print_info(self):
        print(self.title,self.price,self.author)

    def __repr__(self):
        return"<图书:{}>".format(self.title)
if __name__ == "__main__":

     book = Book("python经典","price=29.0",author="tom")
     book2 = Book("Flask")
     book3 = Book("财管")

     del(book3)

     print("图书数量:{}".format(Book.count))

结果是:
图书数量:2
根据年份计算年龄

import datetime

class Student:

    def __init__(self,name,birthdate):
        self.name = name
        self.birthdate = birthdate

    def get_age(self):
        return datetime.date.today().year - self.birthdate.year

if __name__ == "__main__":
    s = Student("TOM",datetime.date(1992,4,1))
    print(s.birthdate)
    print(s.get_age())

结果是:
1992-04-01
27
设置禁止删除

import datetime

class Student:

    def __init__(self,name,birthdate):
        self.name = name
        self.birthdate = birthdate

    @property
    def age(self):
        return datetime.date.today().year - self.birthdate.year
    @age.setter
    def age(self,value):
        raise AttributeError("禁止赋值年龄")
    @age.deleter
    def age(self):
        raise AttributeError("年龄不能删除")


if __name__ == "__main__":
    s = Student("TOM",datetime.date(1992,4,1))
    print(s.birthdate)
    print(s.age)
    s.birthdate = datetime.date(1987,6,13)
    del(s.age)
    print(s.age)

结果是:
Traceback (most recent call last):
File “D:/PY/PY1/.idea/test2.py”, line 41, in
del(s.age)
1992-04-01
File “D:/PY/PY1/.idea/test2.py”, line 33, in age
raise AttributeError(“年龄不能删除”)
AttributeError: 年龄不能删除
27

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值