Python面向对象编程
类和类的属性、方法
import datetime
class Book:
def __init__(self,
title,
price=0.0,
author='',
pubate=datetime.date.today()): # 构造方法,可以给属性赋默认值
self.title = title # self代表类的实例
self.price = price
self.author = author
self.pubate = pubate
def print_info(self): # 类的一般方法
print('本书信息如下:')
print('标题:{}'.format(self.title))
print('价格:{}'.format(self.price))
print('作者:{}'.format(self.author))
print('出版日期:{}\n'.format(self.pubate))
book1 = Book('Python', 29.9, 'Tom', datetime.date(2016, 3, 1))
book1.print_info()
print(book1)
输出:
本书信息如下:
标题:Python
价格:29.9
作者:Tom
出版日期:2016-03-01
<__main__.Book object at 0x000001B63E26E848>
类的名称以大写字母开头,且不要含有下划线
__repr__方法与__str__方法
class Book:
def __init__(self, title, price=0.0, author=''):
self.title = title
self.price = price
self.author = author
def __repr__(self): # 定义在控制台直接输入类的实例对象再回车时的输出;若没使用__str__()方法,则也是使用print()打印的输出
return '<图书{}>'.format(self.title)
def __str__