python里class(类)中object是什么意思

python的class(类)中的object是什么意思?

写object和不写object有什么区别?

示例代码

class Test:
    name = "libai"


class Test1(object):
    name = 'libai'


if __name__ == '__main__':
    test = Test()
    print(dir(test))

    test1 = Test1()
    print(dir(test1))

输出结果

┌──(root㉿kali)-[~/]
└─# python2 test.py
['__doc__', '__module__', 'name']
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name']

┌──(root㉿kali)-[~/]
└─# python3 test.py
['__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__', 'name']
['__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__', 'name']

  • Test类很明显能够看出区别,不继承object对象,只拥有了__doc__ , __module__和自己定义的name变量, 也就是说这个类的命名空间只有三个对象可以操作.

  • Test1类继承了object对象,拥有了好多可操作对象,这些都是类中的高级特性。

在python2.x和python3.x中的输出结果不同,因为python3.x默认已经加了object,而python2.x并没有

posted @ 2023-01-11 21:32  gvpn  阅读(97)  评论(0编辑  收藏  举报