python定义类加不加object区别

python定义类时候加不加object区别

python 2.x

python2有经典类(旧式类)old-style(classic-style)和新式类new-style的区别

写法分别为:

1
2
3
4
5
class A:
...

class A(object):
...

继承object类的类就是新式类,目的就是让自己定义的类有更多的属性(因为本地只有python 3演示不了python 2不继承object类的效果,大概的输出:dir()只能输出'__doc__', '__module__'两个属性,也就是说这个类的命名空间里面只有这两个属性可以操作)

python 3.x

python 3.x默认是继承object类的,不需要声明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env python3
# -*-coding: utf-8 -*-
"""
@author: kyle
@time: 2021/2/26 8:52
"""


class WithoutObject:
# python3.x 默认继承object类
def __init__(self, name):
self.name = name

def __repr__(self):
return self.name


class WithObject1():
# 类无继承情况下,括号可写可不写,python3.x默认继承了object类
def __init__(self, name):
self.name = name

def __repr__(self):
return self.name


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

def __repr__(self):
return self.name


if __name__ == '__main__':
x = WithoutObject('Alice')
print(x, dir(x))

y = WithObject1('Bob')
print(y, dir(y))

z = WithObject2('Carl')
print(z, dir(z))

输出:

1
2
3
4
5
6
Alice ['__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']

Bob ['__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']

Carl ['__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']

为了养成良好的习惯,在定义类的时候,没有特定继承不妨也写出object类算是对自己的一个提示,该类的命名空间有哪些属性是可以操作的。

以上,完~

文章目录
  1. python 2.x
  2. python 3.x
|