Skip to content

Commit ec6cfc3

Browse files
committed
object类的特殊方法与特殊属性
1 parent 79b6a54 commit ec6cfc3

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

exercise/object_test.py

+67
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,31 @@
11
# object类
22

33
class Student:
4+
# __init__:对创建的对象进行初始化
45
def __init__(self, name, age):
6+
print('__init__被调用了,self的id值为:{0}'.format(id(self)))
57
self.name = name
68
self.age = age
79

10+
# __new__:用于创建对象
11+
def __new__(cls, *args, **kwargs):
12+
print('__new__被调用只需了,cls的id值为{0}'.format(id(cls)))
13+
obj = super().__new__(cls)
14+
print('创建的对象的id为{0}'.format(id(obj)))
15+
return obj
16+
817
# __str__方法类似于java中的toString方法
918
def __str__(self):
1019
return '我的名字是{0},今年{1}岁了'.format(self.name, self.age)
1120

21+
# __add__:使对象具有"+"功能
22+
def __add__(self, other):
23+
return self.name + other.name
24+
25+
# __len__:让内置函数的参数可以是自定义类型
26+
def __len__(self):
27+
return len(self.name)
28+
1229

1330
stu = Student('张三', 20)
1431
'''
@@ -18,3 +35,53 @@ def __str__(self):
1835
'''
1936
print(dir(stu))
2037
print(stu)
38+
39+
40+
class A:
41+
pass
42+
43+
44+
class B:
45+
pass
46+
47+
48+
class C(A, B):
49+
def __init__(self, name, age):
50+
self.name = name
51+
self.age = age
52+
53+
54+
x = C('Jack', 20)
55+
# __dict__:获得类对象或实例对象所绑定的所有属性和方法的字典
56+
print(x.__dict__)
57+
print(C.__dict__)
58+
# __class__:输出对象所属的类型
59+
print(x.__class__)
60+
# __bases__:输出父类的元组
61+
print(C.__bases__)
62+
# __base__:输出离的最近父类
63+
print(C.__base__)
64+
# 查看类的层次结构,返回元组类型
65+
print(C.__mro__)
66+
# 查看子类的列表
67+
print(A.__subclasses__())
68+
69+
# __add__:通过重写该方法,可使自定义对象具有"+"的功能
70+
a = 20
71+
b = 100
72+
print(a.__add__(b))
73+
stu1 = Student('张三', 10)
74+
stu2 = Student('李四', 20)
75+
print(stu1 + stu2)
76+
print(stu1.__add__(stu2))
77+
78+
# __len__:重写该方法,让内置函数的参数可以是自定义类型
79+
lst = [11, 22, 33, 44]
80+
print(len(lst))
81+
print(len(stu1))
82+
83+
# __new__:用于创建对象
84+
print('object这个类对象的id为:{0}'.format(id(object)))
85+
print('Student这个类对象的id为:{0}'.format(id(Student)))
86+
stu = Student('张三', 20)
87+
print('stu这个实例对象的id为:{0}'.format(id(stu)))

0 commit comments

Comments
 (0)