###object 根类

object 类是所有类的父类,因此所有的类都有 object 类的属性和方法。我们显然有必要深入研究一下 object 类的结构。对于我们继续深入学习 Python 很有好处。

为了深入学习对象,我们先学习内置函数 dir(),他可以让我们方便的看到指定对象所有的属性

【测试】查看对象所有属性以及和 object 进行比对

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_age(self):
        print(self.name, "的年龄是:", self.age)


obj = object()
print(dir(obj))

s2 = Person("高淇", 18)
print(dir(s2))

输出结果:

D:\work\python\three\venv\Scripts\python.exe D:\work\python\three\mypy17.py 
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name', 'say_age']

从上面我们可以发现这样几个要点:
1. Person 对象增加了六个属性:
__dict__ __module__ __weakref__ age name say_age
2. object 的所有属性,Person 类作为 object 的子类,显然包含了所有的属性。
3. 我们打印 age、name、say_age,发现 say_age 虽然是方法,实际上也是属性。只不过,这个属性的类型是“method”而已。
age <class ‘int’>
name <class ‘str’>
say_age <class ‘method’>

【注】关于 object 这些属性的详细学习,会在后面学习中逐个涉及。在此,无法一一展开。

###重写__str__()方法

object 有一个__str__()方法,用于返回一个对于“对象的描述”,对应于内置函数 str()经常用于 print()方法,帮助我们查看对象的信息。__str__()可以重写。

class Person:
    def __init__(self, name, age):
        self.name = name
        self.__age = age

    def __str__(self):
        """将对象转化成一个字符串,一般用于 print 方法"""
        return "名字是:{0},年龄是{1}".format(self.name, self.__age)


p = Person("高淇", 18)
print(p)

输出结果:

D:\work\python\three\venv\Scripts\python.exe D:\work\python\three\mypy18.py 
名字是:高淇,年龄是18

 

原文地址:http://www.cnblogs.com/yuanzijian/p/16910506.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性