python笔记-面向对象(二)

魔术方法-析构函数

析构函数,str和repr方法

class People(object):
    # 实例化对象时自动执行
    def __init__(self, name, age):
        # 把属性和对象名绑定在一起, 便于访问对象的属性.
        self.name = name
        self.age = age
        print("创建对象成功.......")
    #  析构函数, 当你删除对象时, 自动调用的方法。
    #   del 对象名或者程序执行结束之后
    def __del__(self):
        print("删除对象成功.......")
    #  __str__和__repr__都是对对象的字符串显示, 使用场景不同.
    # 如果没有__str__的时候, 自动调用__repr__方法的内容.

    def __str__(self):
        # print(对象名)   print(str(对象名))
        # print('People(%s, %d)' %(self.name, self.age))
        return  'People(%s, %d)' %(self.name, self.age)

    def __repr__(self):
        # print(repr(对象名))  或者交互式环境中直接: 对象名
        return  "People(%s)" %(self.name)
    def __hello(self):
        print("hello")

    def world(self):
        self.__hello()

if __name__ == '__main__':
    # 创建对象
    p1 = People('fentiao', 12)
    print(p1)
    print(p1.__str__())
    p1.world()
    print(str(p1))
    print(repr(p1))
    # 删除对象
    del p1

图书管理系统

# 假设每本书只有一本

class Book(object):
    def __init__(self, name, author, state, bookIndex):
        self.name = name
        self.author = author
        # 0:'已借出' 1:'未借出'
        self.state = state
        self.bookIndex = bookIndex


    def __str__(self):
        return  'Book(%s, %d)' %(self.name, self.state)

class   BookManage(object):
    # 存放所有书籍信息, 列表里面存放的是Book对象
    books = []

    def start(self):
        """图书管理系统初始化数据"""
        self.books.append(Book('python', 'Guido', 1, 'IN23445'))
        self.books.append(Book('java', 'Guido1', 1, 'IN23445'))
        self.books.append(Book('C++', 'Guido2', 1, 'IN23445'))
        print("初始化数据成功!")

    def Menu(self):
        """图书管理菜单栏"""
        while True:
            print("""
                        图书管理操作

            1). 添加书籍
            2). 删除数据
            3). 查询书籍
            4). 退出
            """)
            choice = input("请输入你的选择:")
            if choice == '1':
                self.addBook()
            elif choice == '2':
                self.delBook()
            elif choice == '3':
                self.borrowBook()
            elif choice == '4':
                exit()
            else:
                print("请输入正确的选择!")

    def addBook(self):
        print("添加书籍".center(0, '*'))
        name = input("书籍名称:")
        bObj = self.isBookExist(name)
        if bObj:
            print("书籍%s已经存在" %(bObj.name))
        else:
            self.books.append(Book(name,input("作者:"), 1, input("存放位置:")))
            print("书籍%s添加成功" %(name))

    def delBook(self):
        print("删除书籍".center(50,'*'))
        for i in self.books:
            print(i)
        name = input("删除书籍名称:")
        a = self.isBookExist(name)
        if a:
            self.books.remove(a)
            print("删除%s成功" %(a))
        else:
            print("书籍不存在")

    def borrowBook(self):
        print("查询书籍".center(50,'*'))
        for i in self.books:
            print(i)
        name = input("查询书籍名称:")
        b = self.isBookExist(name)
        for book in self.books:
            if book == b:
                print(book)
                break
            else:
                print("%s不存在" %(b))
                break
    def isBookExist(self, name):
        """检测书籍是否存在"""
        # 1. 依次遍历列表books里面的每个元素
        # 2. 如果有一个对象的书名和name相等, 那么存在;
        # 3. 如果遍历所有内容, 都没有发现书名与name相同, 书籍不存在;
        for book in self.books:
            if book.name == name:
                # 因为后面需要
                return book
        else:
            return  False

if __name__ == "__main__":
    bManger = BookManage()
    bManger.start()
    bManger.Menu()

format魔术方法

formats = {
    'ymd':"{d.year}-{d.month}-{d.day}",
    'mdy':"{d.month}/{d.day}/{d.year}",
}


class Date(object):
    def __init__(self, year, month, day):
        self.year = year
        self.month = month
        self.day = day

    # format方法: format(对象名)时自动调用
    def __format__(self, format_spec=None):
        # return "这是显示format的内容"
        # if format_spec:
        #     format_spec = format_spec
        # else:
        #     format_spec = 'ymd'
        if not format_spec:
            format_spec = 'ymd'
        fmt = formats[format_spec] # "{d.year}-{d.month}-{d.day}".format(d=d)
        return  fmt.format(d=self)

d = Date(2019, 8, 25)
print(format(d))
print(format(d, 'mdy')) # ‘mdy’ ===> '8/25/2019'

print(d.__format__('ymd'))
print(format(d, 'ymd')) # ‘ymd’ ===> ‘2019-8-25’

字符串的format方法

print("name:%s, age:%d, scores:%s" % ('westos', 10, dict(a=1, b=2)))
print("name:%s, age:%d, scores:%s" % ('westos', 10, (1, 2)))
print("name:%s, age:%d, name:%s" % ('westos', 10, 'westos'))

# 通过位置填充字符串
print("name:{0}, age:{1}, scores:{2}".format('westos', 10, [100, 100, 100]))
print("name:{0}, age:{1}, scores:{0}".format('westos', 10))
print("name:{0}, id:{1:.3f}, scores:{0}".format('westos', 19.2332435))

# 通过key值填充字符串
d = {'max': 100, 'min': 10}
print("MAX: {max}, MIN:{min}".format(max=100, min=10))
print("MAX: {max}, MIN:{min}".format(**d))

# 通过下标或者索引值填充
point = (3,4)
print("x:{0[0]}, y:{0[1]}".format(point))


# 面向对象操作
class Book(object):
    def __init__(self, name, author, state, bookIndex):
        self.name = name
        self.author = author
        # 0:'已借出' 1:'未借出'
        self.state = state
        self.bookIndex = bookIndex

    def __str__(self):
        return  'Book(%s, %d)' %(self.name, self.state)
b = Book('python', 'guido', 1, 'IND444')
print("name:{b.name}, state:{b.state}, author:{b.state}".format(b=b))
print("name:{0.name}, state:{0.state}, author:{0.state}".format(b))

类内部装饰器 property

没有使用装饰器property的情况下

class Book(object):
    def __init__(self, name, author, state, bookIndex):
        self.name = name
        self.author = author
        # 0:'已借出' 1:'未借出'
        self.__state = state
        self.bookIndex = bookIndex

    def get_state(self):
        if self.__state == 0:
            return  '已借出'
        elif self.__state == 1:
            return  '未借出'
        else:
            return  "状态异常"

    def set_state(self, value):
        # if value == 0 or value == 1:
        if value in (0,1):
            # 更新书籍的状态
            self.__state = value

    def del_state(self):
        print("is deleteing......")

    def __str__(self):
        return  'Book(%s, %d)' %(self.name, self.__state)

    state = property(fget=get_state, fset=set_state, fdel=del_state)

b = Book('python', 'guido', 1, 'chddf')

print(b.state)
b.state = 0
print(b.state)

del  b.state

使用装饰器property时

class Book(object):
    def __init__(self, name, author, state, bookIndex):
        self.name = name
        self.author = author
        # 0:'已借出' 1:'未借出'
        self.__state = state
        self.bookIndex = bookIndex

    # 将类方法变成类属性
    # 使用时, 没有装饰器时:b.state()
    # 使用时, 有装饰器时:b.state
    @property
    def state(self):
        if self.__state == 0:
            return  '已借出'
        elif self.__state == 1:
            return  '未借出'
        else:
            return  "状态异常"
    # 当修改属性state时, 自动执行下面的方法; b.state = 10
    @state.setter
    def state(self, value):
        # if value == 0 or value == 1:
        if value in (0,1):
            # 更新书籍的状态
            self.__state = value

    @state.deleter
    def state(self):
        print("is deleteing......")

    def __str__(self):
        return  'Book(%s, %d)' %(self.name, self.__state)

b = Book('python', 'guido', 1, 'chddf')
print(b.state)
# 1). 书籍的状态可以人以改变, 并不能限制只能为0或者1;
# 2). 书籍状态如何友好的显示?
b.state = 10
print(b.state)

print(b.state)
b.state = 0
print(b.state)

del  b.state

类的索引,切片,成员操作符

索引

# str, list
li = [1,2,3,4,5,6]
__getitem__:  li[0]   === __getslice__
__setitem__: li[0] = 10  == __setslice__
__delitem__: del li[0]   == __delslice__]


class Student(object):
    def __init__(self, name, scores):
        self.name = name
        self.scores = scores

    # 支持索引; s[index]
    def __getitem__(self, index):
        # print("获取索引对应的value值")
        return  self.scores[index]


    # s[索引] = 修改的值
    def __setitem__(self, index, value):
        self.scores[index] = value

    # del s[索引]
    def __delitem__(self, index):
        del self.scores[index]


    def hello(self):
        return  "hello"
s = Student('westos', [101, 100, 100])


# *********************************index**************************
print(s[0])
print(s[1])
print(s[2])

# 0, 200
s[0] = 200
print(s[0])


print(s.scores)
del s[0]
print(s.scores)

字典的索引

class Student(object):
    def __init__(self, name, scores):
        self.name = name
        self.scores = scores

    # 支持索引; s[key]
    def __getitem__(self, key):
        # print("获取索引对应的value值")
        return  self.__dict__[key]

    # s[key] = 修改的值
    def __setitem__(self, key, value):
        self.__dict__[key] = value

    # del s[key]
    def __delitem__(self, key):
        del self.__dict__[key]

    def hello(self):
        return  "hello"
s = Student('westos', [101, 100, 100])

#**************************key获取value值***********************
# 可以获取所有的属性为key值, 以及对应的value值, 并封装为一个字典返回.
# print(s.__dict__)
print(s['name'])
print(s['scores'])

s['name'] = 'westo1'
print(s['name'])

del s['name']
print(s['name'])

切片

class Student(object):
    def __init__(self, name, scores):
        self.name = name
        self.scores = scores
    def __getitem__(self, key):
        return self.scores[key]
    def __setitem__(self, key, value):
        self.scores[key] = value
    def __delitem__(self, key):
        del self.scores[key]

# 对于切片的操作*******
s = Student('westos', [101, 90, 101])
print(s[1:3])
s[1:3] = [0,0]
print(s[:])
del s[:-1]
print(s[:])
print(s[0])

重复,连接,成员操作符

class Student(object):
    def __init__(self, name, scores):
        self.name = name
        self.scores = scores
        self.power = 100
    # obj1 + obj2
    def __add__(self, other):
        # 更新self对象的power属性值;
        self.power =  self.power + other.power
        return  self
    # obj1 * 3
    def __mul__(self, other):
        # *的效果是, 能量*power
        return  self.power * other
    # 成员操作符; item in obj1
    def __contains__(self, item):
        return  item in self.scores
    # 可以for循环迭代
    def __iter__(self):
        """
        iter([1,2,3,4,5])
        <list_iterator object at 0x7f6e1f51ffd0>
        iter({1,2,3,4,5})
        <set_iterator object at 0x7f6e1f567318>

        """
        # 迭代返回的是成绩
        return  iter(self.scores)
    def __repr__(self):
        return  "Student:%s,%s" %(self.name, self.power)
print("hello " + "world")
print([1,2,3] + [3,4,5])

s1 = Student('westos1', [101,100,100])
s2 = Student('westos2', [100,100,100])
s3 = Student('westos3', [100,100,100])

# 连接的实现;
# "hello" + "world" + "hwllo"
print(s1 + s2 + s3)
# a = 1 ; a+=1 a=2
# str = "h"; str+='e' str=''he
s1 += s2
print(s1)


# 重复:
a = 3
print(a*3)
s = 'a'
print(s*3)
li = [1,2,3]
print(li*3)
print(s1*3)


# 成员操作符
print(s1.scores)
print(200 in s1)
print(100 in s1)
print(200 not in s1)
print(100 not in s1)

# for循环迭代
for i in s1:
    print(i)
print(isinstance(s1, Iterable)

call方法

# 实现一个单例模式====
from django.core.paginator import Page


class Student(object):
    def __init__(self, name, scores, power):
        self.name = name
        self.scores = scores
        self.power = power
    def __call__(self, *args, **kwargs):
        return "对象被调用......"
    # class: 实例化对象之前执行
    def __new__(cls, *args, **kwargs):
        # 判断是否obj对象是否已经被创建, 如果没有被创建, 则创建,
        if not hasattr(cls, 'obj'):
            cls.obj = object.__new__(cls)
        # 如果已经创建成功,则返回创建好的对象
        return  cls.obj
s1 = Student('westos1', [101,100,100], 100)
s2 = Student('westos1', [101,100,100], 100)
print(s1)
print(s2)

猜你喜欢

转载自blog.csdn.net/qq_42687283/article/details/82423269
今日推荐