zoukankan      html  css  js  c++  java
  • Python实用笔记 (26)面向对象高级编程——定制类

    Python的class允许定义许多定制方法,可以让我们非常方便地生成特定的类。以下是集中常见的定制方法:

    怎么才能打印得好看呢?只需要定义好__str__()方法,返回一个好看的字符串就可以了:

    __str__()

    >>> class Student(object):
    ...     def __init__(self, name):
    ...         self.name = name
    ...     def __str__(self):
    ...         return 'Student object (name: %s)' % self.name
    ...
    >>> print(Student('Michael'))
    Student object (name: Michael)
    

    这样打印出来的实例,不但好看,而且容易看出实例内部重要的数据。

    但是细心的朋友会发现直接敲变量不用print,打印出来的实例还是不好看:

    >>> s = Student('Michael')
    >>> s
    <__main__.Student object at 0x109afb310>
    

    这是因为直接显示变量调用的不是__str__(),而是__repr__(),两者的区别是__str__()返回用户看到的字符串,而__repr__()返回程序开发者看到的字符串,也就是说,__repr__()是为调试服务的。

    解决办法是再定义一个__repr__()。但是通常__str__()__repr__()代码都是一样的,所以,有个偷懒的写法:

    class Student(object):
        def __init__(self, name):
            self.name = name
        def __str__(self):
            return 'Student object (name=%s)' % self.name
        __repr__ = __str__
    
  • 相关阅读:
    逆序对的相关问题:bzoj1831,bzoj2431
    bzoj3211,bzoj3038
    hdu 1179最大匹配
    hdu 3038带权并查集
    poj 1733离散化(map)+并查集
    codeforces 369B
    poj 1456
    POJ 1988相对偏移
    poj 1986tarjan模板题
    poj 1330lca模板题离线算法
  • 原文地址:https://www.cnblogs.com/niulang/p/9013252.html
Copyright © 2011-2022 走看看