Python基础–17
特殊方法和特殊属性
print(dir(object))
# ['__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 A:
pass
class B:
pass
class C(A,B):
def __init__(self,name):
self.name=name
x=C('Jack')
print(x.__dict__) #{'name': 'Jack'}
print(C.__dict__)#{'__module__': '__main__', '__init__': <function C.__init__ at 0x000001C1EF107700>, '__doc__': None}
print(x.__class__)#对象所属类<class '__main__.C'>
print(C.__bases__)#父类元组(<class '__main__.A'>, <class '__main__.B'>)
print(C.__base__)#基类元组<class '__main__.A'>
print(C.__mro__)#类的层次结构(<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)
print(B.__subclasses__())#子类[<class '__main__.C'>]
a=20
b=100
c=a+b
d=a.__add__(b)
print(c)#120
print(d)#120
class Student:
def __init__(self,name):
self.name=name
def __add__(self,other):
return self.name+other.name
def __len__(self):
return len(self.name)
stu1=Student('张三')
stu2=Student('李四')
#print(stu1+stu2)TypeError: unsupported operand type(s) for +: 'Student' and 'Student'
print(stu1+stu2)#张三李四
#实现了两个对象的加法运算,在类中编写了add特殊的方法
print(len(stu1))#TypeError: object of type 'Student' has no len()
#2 在类中编写了len特殊的方法,return len(self.name)
new / init
class Person(object):
def __new__(cls, *args, **kwargs): #创建对象
print('__new__被调用执行了,cls的id值为{0}'.format(id(cls))) #4864
obj=super().__new__(cls)
print('创建的对象的id为:{0}'.format(id(obj))) #7264
return obj
def __init__(self,name,age): #对创建的对象初始化
self.name=name
self.age=age
print(' _init__被调用了,self的id为:{0}'.format(id(self))) #7264
print('object id:{0}'.format(id(object))) #4048
print('Person id:{0}'.format(id(Person))) #4864
p1=Person('三',20)
print('p1 id:{0}'.format(id(p1))) #7264
# object id:140709592514048
# Person id:2701662344864
# __new__被调用执行了,cls的id值为2701662344864
# 创建的对象的id为:2701663637264
# _init__被调用了,self的id为:2701663637264
# p1 id:2701663637264
类的赋值与浅拷贝
#类对象的赋值操作,形成两个变量,实际上还是指向同一个对象
cpu1=CPU()
cpu2=cpu1
print(cpu1)
print(cpu2)
# <__main__.CPU object at 0x0000021A25626FD0>
# <__main__.CPU object at 0x0000021A25626FD0>
disk=Disk()
computer=Computer(cpu1,disk)
import copy
computer2=copy.copy(computer) #浅拷贝,对象包含的子对象内容不拷贝
computer3=copy.deepcopy(computer) #深拷贝,递归拷贝对象中包含的子对象
print(computer,computer.cpu,computer.disk)
print(computer2,computer2.cpu,computer2.disk)
print(computer3,computer3.cpu,computer3.disk)
# <__main__.Computer object at 0x000002281D258F70> <__main__.CPU object at 0x000002281D258FD0> <__main__.Disk object at 0x000002281D258FA0>
# <__main__.Computer object at 0x000002281D258820> <__main__.CPU object at 0x000002281D258FD0> <__main__.Disk object at 0x000002281D258FA0>
# <__main__.Computer object at 0x000002281D258730> <__main__.CPU object at 0x000002281D258430> <__main__.Disk object at 0x000002281D258460>