Seventh (2): object-oriented programming

Object-Oriented

1, step

OOA OOA

OOD OOD

OOP Object Oriented Programming

def search_book(title):
    print('搜索包含书关键词{}的图书'.format(title))
book = {
    'title':'Python入门',
    'price':39.00,
    'author':"Peter",
    'search_book':search_book
}
print(book['title'])
print(book.get('price', 0.0))
book.get('search_book')('Python')  #在这个.get方法后面记得加上传递参数的值,因为调用的search_book函数这个需要输入参数
Python入门
39.0
搜索包含书关键词Python的图书

2, to achieve

Object behavior analysis feature

Written description of the object class template

Instantiation, simulation

import datetime
class Book:  #长的命名就连在一起,在第二个单词开头大写,不在词中间添加下划线
    def __init__(self,title,
                 price=0.0,
                 author='',
                 publisher=None,
                 pubdate=datetime.date.today()):  #这种有一两个下划线开头结尾的叫预定义
        self.title = title  #定义了对象的特征
        self.price = price
        self.author = author
        self.publisher = publisher
        self.pubdate = pubdate
    def __repr__(self):
        return '<图书 {} at 0x{}>'.format(self.title,id(self))
    def print_info(self):
        print('当前这本书的信息如下:')
        print('标题:{}'.format(self.title))
        print('定价:{}'.format(self.price))
        print('作者:{}'.format(self.author))
        print('出版社:{}'.format(self.publisher))
        print('出版时间:{}'.format(self.pubdate))      
book1 = Book('C#精典',29.9,'Tom','优品课堂',datetime.date(2016,3,1))
book1.print_info()
当前这本书的信息如下:
标题:C#精典
定价:29.9
作者:Tom
出版社:优品课堂
出版时间:2016-03-01
book = Book('ASP.NET')
book.title
book.pubdate
book.price
book
'ASP.NET'
datetime.date(2019, 9, 4)
0.0
<图书 ASP.NET at 0x1935503916224>

Guess you like

Origin www.cnblogs.com/linyk/p/11462222.html