python面向对象

本文介绍了Python中的面向对象编程概念,包括面向对象和面向过程的区别,深入探讨了类的创建、封装、继承和多态,详细讲解了新式类与经典类的差异。此外,还讨论了魔术方法的应用,如初始化、字符串表示、索引和切片操作。最后,通过图书管理系统实例展示了类的实际应用,包括类属性、类方法和静态方法的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、面向对象和面向过程

  • 面向对象编程—Object Oriented Programming,简称OOP,把对象作为程序的基本单元,一个对象包含了数据和操作数据的函数;
  • 面向过程把函数继续切分为子函数,来降低系统的复杂度;

二、类

1.类的创建 父类(基类)和子类(派生类)
##针对不同对象,特色化设置
class Cat(object): ##所有类的父类均可为object
    # print('hello')  ##定义类时会执行
    ## attribute:属性,把属性和对象绑定在一起
    def __init__(self,name,age,high):  ##self -> 
        self.name = name
        self.age = age
        self.high = high

baozi=Cat('baozi',3,20)  ##实例化对象(Instance)
print(baozi.age)  ##通过对象名获取属性值
print(baozi.name)
print(baozi.high)
2.封装
  • 数据和逻辑被“封装”起来了,调用很容易,不用知道内部实现的细节;
  • 封装的另一个好处是可以给类增加新的方法;
class Cat(object):  ##封装:将属性绑定在self变量上
    def __init__(self,name,age,high):
        self.name = name
        self.age = age
        self.high = high
##类里面的参数self,pyhton解释器会自动将变量传递给self变量
    def eat(self):
        print(self.name+' is eatting happy')

baozi = Cat('baozi',2,11)
# baozi.name  #直接调用
# self.name   #selfbianl间接调用
3.继承和多态
class Animals(object):
    def __init__(self,name,age):  ##属性
        self.name = name  
        self.age = age

    def eat(self):   ##方法
        print(self.name+' is eatting happy')

class Cat(Animals):  ##继承父类的全部功能
##调用函数时,优先调用子类函数;子类没有则调用父类,依次类推
    def __init__(self,name,age,weight):  
        # Animals.__init__(name,age)  ##执行父类的构造函数
        super(Cat, self).__init__(name,age)  ##注意:python2不行
        self.weight = weight
##多态:子类的覆盖了父类的方法
    def eat(self):
        print(self.name+' is bbb.....')

baozi = Cat('baozi',2,11)
baozi.eat()
4.新式类和经典类
  • pyhton3:都是新式类
  • python2:新式类和经典类
  • 新式类:广度优先 A -> B,C -> (B->D)|(C->D)
  • 经典类:深度优先 A -> B -> D -> C -> D
class D:
    # pass
    def test(self):
        print("D test")
class C(D):
    # pass
    def test(self):
        print("C test")
class B(D):    ##父类B没有定义,依次查找上一级
    pass
    # def test(self):
    #     print("B test")
class A(B,C):  ##A实例化的时候,调用函数test时,查找父类的函数
    pass
    # def test(self):
    #     print("A test")

a_t = A()  ##python2中,输出:D test
a_t.test() ##python3中,输出:C test

三、魔术方法

1.常用魔术方法
  • def _init_(self): 封装
  • def _str_(self): 字符串显示,自动调用
  • def _getitem_(self, item): 实例化对象可以索引和切片
  • def _setitem_(self, key, value): 实例化对象可以通过索引和切片修改值
  • def _delitem_(self, key): 实例化对象可以通过索引和切片删除值
class Student(object):
    ##oop:封装
    def __init__(self, name, score):  
        self.name = name
        self.score = score
        self.score_avg = sum(self.score) / len(self.score)
    ##str:对象的字符串显示,执行str(对象)或print(对象)时自动调用
    def __str__(self):
        pass
    ##添加__getitem__魔术方法,该类对象实例化的时候可以索引和切片
    def __getitem__(self, item):
        return self.score[item]
    ##添加__setitem__魔术方法,该类对象实例化的时候可以通过索引和切片修改值
    def __setitem__(self, key, value):
        self.score[key] = value
    ##添加__delitem__魔术方法,该类对象实例化的时候可以通过索引和切片删除值
    def __delitem__(self, key):
        del self.score[key]
2.slice内置方法
>>> a = slice(1,10,2)
>>> List = list(range(10))
>>> List
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> List[a]  ##类似切片功能
[1, 3, 5, 7, 9]
>>> List[1:10:2]
[1, 3, 5, 7, 9]

四、图书管理系统

1.简易版:
class Book(object):
    def __init__(self, name, author, state, index):  
        self.name = name   ##封装图书信息
        self.author = author
        self.state = state
        self.index = index

    def __str__(self):   ##将0,1状态转化为借出和为借出
        if self.state == 0:
            state = 'IN'
        else:
            state = 'OUT'

        return 'Book(%s,%s,%s,%s)' % (self.name, self.author, state, self.index)

class BookManage(object):
    BookList = []   ##图书信息列表,储存对象类型

    def addbook(self):  ##将对象类型的图书信息加入列表
        """Add a new Book"""
        print('New Book Adding'.center(40, '*'))
        name = input('Please input the book name: ')
        author = input('Please input the book author: ')
        index = input('Please input the book position: ')
        self.BookList.append(Book(name, author, 0, index)) 
        print(name + ' is Added Sucessfully!')

    def borrowbook(self):
        """Borrow Books"""
        print('Borrow Book'.center(40, '*'))
        name = input('Please input the book name what you want to berrow: ')
        for book in self.BookList: ##可调用checkbook函数,效果一样
            if name == book.name:  ##遍历,判断借阅的图书是否存在
                book.state = 1     ##借出之后,状态变为1
                print(name + ' is Borrowed OK1')
            else:
                print(name + ' is not exist!!')

    def checkbook(self, name):  ##定义checkbook函数,判断图书是否存在
        """Check the message of Book"""
        print('Book Messages'.center(40, '*'))
        for book in self.BookList:
            if name == book.name:
                return book
        else:
            return None

    def usercheck(self):  ##查找图书信息
        name = input('Please input the book name what you want to check: ')
        BookRes = self.checkbook(name)
        if BookRes:
            print(name + ' has been found!')
            print(BookRes)
        else:
            print(name + ' is not exist!!')

    def viewbook(self):   ##遍历显示图书收藏信息
        """View the BookList"""
        print('View Books'.center(40, '*'))
        for book in self.BookList:
            print(book)

bm = BookManage()   ##实例化
bm.addbook()        ##调用类的函数
# bm.addbook()
bm.borrowbook()
# bm.usercheck()
bm.viewbook()
2.基础提升版:
  • 优化管理系统,加入循环;
  • 优化图书借阅模块;
  • 函数优化,可移植;
class Book(object):
    def __init__(self, name, author, state, index):
        self.name = name
        self.author = author
        self.state = state
        self.index = index

    def __str__(self):
        if self.state == 0:
            state = 'IN'
        else:
            state = 'OUT'

        return 'Book(%s,%s,%s,%s)' % (self.name, self.author, state, self.index)

class BookManage(object):
    BookList = []

    def initBook(self):  ##初始化图书信息
        self.BookList.append(Book('python', 'Guido', 0, 'PY001'))
        self.BookList.append(Book('Java', 'Guido', 1, 'JA001'))
        self.BookList.append(Book('Linux', 'Linus', 0, 'LI001'))

    def menu(self):  ##定义menu函数,进行循环

        info = """
                    BookManage System
                1. add
                2. borrow
                3. check
                4. view
                5. delete
                6. exit
    Please input your choice:  """
        while True:   ##根据用户的选择执行不同操作
            choice = input(info)
            if choice == '1':
                self.addbook()
            elif choice == '2':
                self.borrowbook()
            elif choice == '3':
                self.usercheck()
            elif choice == '4':
                self.viewbook()
            elif choice == '5':
                self.deleteBook()
            elif choice == '6':
                exit(0)

    def addbook(self):  ##添加图书信息
        """Add a new Book"""
        print('New Book Adding'.center(40, '*'))
        name = input('Please input the book name: ')
        author = input('Please input the book author: ')
        index = input('Please input the book position: ')
        self.BookList.append(Book(name, author, 0, index))
        print(name + ' is Added Sucessfully!')

    def borrowbook(self):  ##借阅模块优化
        """Borrow Books"""
        print('Borrow Book'.center(40, '*'))
        name = input('Please input the book name what you want to berrow: ')
        BookRes = self.checkbook(name)
        if BookRes:  ##判断图书是否存在,调用checkbook函数
            if BookRes.state == 0:  ##判断图书状态,是否借出
                BookRes.state = 1   #3成功借出,更改图书状态
                print(name + ' is Borrowed OK1')
            else:
                print(name + ' is already borrowed!!')
        else:
            print(name + ' is not exist!!')

    def checkbook(self, name):  ##判断图书是否存在,返回不同值
        """Check the message of Book"""
        print('Book Messages'.center(40, '*'))
        for book in self.BookList:
            if name == book.name:
                return book
        else:
            return None

    def usercheck(self):  ##查询图书信息
        name = input('Please input the book name what you want to check: ')
        BookRes = self.checkbook(name)
        if BookRes:       ##图书存在,显示当前图书信息
            print(name + ' has been found!')
            print(BookRes)
        else:
            print(name + ' is not exist!!')

    def viewbook(self):  ##遍历显示所有图书信息
        """View the BookList"""
        print('View Books'.center(40, '*'))
        for book in self.BookList:
            print(book)

    def deleteBook(self):
        pass

def main():  ##定义main函数
    bm = BookManage()    ##实例化
    bm.initBook()        ##初始化
    print('Systemd OK')
    bm.menu()            ##调用menu函数,进入管理系统

if __name__ == '__main__':  ##判断的是这个脚本内容是否为被导入的模块内容
    main()

五、类操作

1.类属性
  • 1、私有属性:只能在类中使用的属性(双下划线__)
    self.__state = state
  • 2、私有方法:只能在类中使用的方法(双下划线__)
    def get__state(self):
  • 代码示例:
class Book(object):
    def __init__(self, name, author, state, index):
        self.name = name
        self.author = author
        self.__state = state  ##私有属性,类外部不能调用
        self.index = index

    def get__state(self):  ##私有方法,类外部不能调用
        if self.__state == 0:
            return 'IN'
        if self.__state == 1:
            return 'OUT'

    def set__state(self, value):  ##私有方法,类外部不能调用
        if value in [0, 1]:
            self.__state = value
            return True
        else:   ##raise:抛出异常
            raise Exception('The State has been in [0/1]')

book1 = Book('linux', 'lee', 0, 'DT3435')  ##实例化
book.__sate                ##会报错,不能调用state
print(book1.get__state())  ##调用函数繁琐
book1.set__state(3)        ##3不符合state要求,会抛出异常
print(book1.get__state())
  • 3、类属性装饰器 @property
class Book(object):
    def __init__(self, name, author, state, index):
        self.name = name
        self.author = author
        self.__state = state
        self.index = index

    @property  ##代表state不是方法,是一个属性值, book1.state
    def state(self):
        if self.__state == 0:
            return 'IN'
        if self.__state == 1:
            return 'OUT'

    @state.setter  ##book.state = value 赋值或修改
    def state(self, value):
        if value in [0, 1]:
            self.__state = value
            return True
        else:
            raise Exception('The State has been in [0/1]')

book1 = Book('linux', 'lee', 0, 'DT3435')  ##实例化
print(book1.state)  ##类属性装饰器装饰后,可直接调用,并对state做了限制
book1.state = 1
print(book1.state)
2.类方法和静态方法
class Date(object):
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    def date_show(self):  ##self是对象
        print("""
        Year:%s
        Month:%s
        Day:%s""" % (self.year, self.month, self.day))

    @classmethod  ##默认第一个参数是类名
    def date_str(cls, str):  ##类方法,传入cls,实质是Date类
        if '-' in str:
            year, month, day = str.split('-')
        if '/' in str:
            month, day, year = str.split('/')
        return cls(year, month, day)

    @staticmethod ##静态方法,pyhton解释器不会传入任何参数
    def date_is_vaild(str):
        if '-' in str:
            year, month, day = map(int, str.split('-'))
        if '/' in str:
            month, day, year = map(int, str.split('/'))
        return year > 0 and 0 < month <= 12 and 0 < day <= 31

##针对不同类型的输入方式实例化
date1 = Date(2018,6,8)  ##以int型数字实例化
date1.date_show()

date2 = Date.date_str('2018-6-8')  ##以str型实例化
date2.date_show()

date3 = Date.date_is_vaild('6/88/2018')  ##简易判断日期是否合法
print(date3)
3.类的自省
type(d1)  ##查看d1的类型
isinstance(d1,Date)   ##查看d1是否为Date类
dir(d1)   ##查看d1的用法
 d1.__class__  ##查看d1的类名
 d1.__doc__    ##查看d1的解释说明
 d1.__dict__   ##查看d1的属性,字典形式列出
 hasattr(d1,'year')     ##d1是否具有year属性
 getattr(d1,'year')     ##查看d1的year属性的值
 getattr(d1,'year''YEAR')  ##若没有year属性,则输出YEAR
 setattr(d1,'year',2000)     ##将d1的year属性值改为2000
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值