day-18 5个内置方法

# 1.  __str__方法:
class Goods:
    def __str__(self):
        return 'apple'
g = Goods()
print(g)             #apple,省略写法
print(g.__str__())   #apple
print(str(g))        #apple,  str(g)相当于g.__str__()
print('%s'%g)        #apple,  str(g)相当于g.__str__()

# 2. __repr__方法:是__str__方法的备胎,当类中没有__str__方法的时候,依然可以调用__str__方法。
class Goods:
    def __repr__(self):
        return 'apple'
g = Goods()
print(g)           #apple
print(g.__str__()) #apple
print(str(g))      #apple
print('%s'%g)     #apple

print(g.__repr__())#apple
print(repr(g))     #apple  ,相当于g.__repr__()
print('%r'%g)     #apple  ,相当于g.__repr__()

# 3. __len__方法:
class Goods:
    def __init__(self,name):
        self.name = name
        self.color = []
    def __len__(self):
        return '%s有%s种颜色'%(self.name,len(self.color))
apple = Goods('apple')
apple.color.append('red')
apple.color.append('green')
print(len(apple.color)) # 2, len(obj)相当于obj.__len__方法

# 4. __del__方法:
class Goods:
    def __del__(self):
        print('删除商品')
apple = Goods()
del apple #删除商品,先调用__del__方法,打印出‘删除商品’,接着删除apple对象。
print(apple) #name 'apple' is not defined

class A:
    def __del__(self): #析构函数:在删除一个对象之前进行收尾工作
        self.f.close()
a = A()
a.f = open() #a.f 拿到一个文件操作符然后存放在内存中,open()打开文件
del a #del先执行方法,后删除a

# 5. __call__方法:obj()就可以调用此方法。
class Goods:
    def __call__(self):
        print('调用方法')
apple = Goods()
apple() #调用方法

猜你喜欢

转载自www.cnblogs.com/python-daxiong/p/11242592.html