文章目录
封装
封装、继承、多态
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