面向对象编程OOP 02
1、
class Book:
# 默认值放在赋值之后
def __init__(self,
title,
price=0.0,
author=' ',
publisher=None):
# 这本书的标题等于你传过来的标题
self.title=title
self.price=price
self.author=author
self.publisher=publisher
# 行为
def print_info(self):
print(self.title,
self.price,
self.author,
self.publisher)
if __name__=='__main__':
book=Book('python精典',29.9,'TOM','清华大学出版社')
book.print_info()
输出结果:
python精典 29.9 TOM 清华大学出版社
3、book计数
class Book:
count=0
# 默认值放在赋值之后(初始化执行)
def __init__(self,title,price=0.0,author=' ',publisher=None):
# 这本书的标题等于你传过来的标题
self.title=title
self.price=price
self.author=author
self.publisher=publisher
Book.count += 1
#__reper__:开发人员调试用(控制台执行)
def __reper__(self):
return '《图书{}at{}》'.format(self.title, id(self))
#__str__:让用户看得明白(打印执行)
def __str__(self):
return '[图书:{},定价:{}]'.format(self.title, self.price)
def print_info(self):
print(self.title,self.price,self.author,self.publisher)
if __name__=='__main__':
book1=Book('python精典',29.9,'TOM','清华大学出版社')
book2=Book('flask')
book3=Book('ASP.net')
print('图书数量:{}'.format(Book.count))
输出结果:
图书数量:3
4、删掉一本书后计数(del)
class Book:
count=0
# 默认值放在赋值之后(初始化执行)
def __init__(self,title,price=0.0,author=' ',publisher=None):
# 这本书的标题等于你传过来的标题
self.title=title
self.price=price
self.author=author
self.publisher=publisher
Book.count += 1
#删除对象执行
def __del__(self):
Book.count -=1
#__reper__:开发人员调试用(控制台执行)
def __reper__(self):
return '《图书{}at{}》'.format(self.title, id(</