Python面向对象编程

本文深入探讨了Python的面向对象编程,包括类和类的属性、方法,详细讲解了__repr__和__str__方法,阐述了静态属性的使用。此外,还介绍了实例方法、类方法和静态方法的区别,以及如何利用property属性进行属性访问控制。同时,文章讨论了类的继承和创建类的属性为另一个类的实例的场景。
摘要由CSDN通过智能技术生成

类和类的属性、方法

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__
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值