day-18 5 built Method

# 1. Method __str__: 
class Goods:
     DEF  __str__ (Self):
         return  ' Apple ' 
G = Goods ()
 Print (G)              # Apple, omitted writing 
Print (. G __str__ ())    # Apple 
Print (STR (G) )         # Apple, STR (G) corresponds to the STR __ .__ G () 
Print ( ' % S ' % G)         # Apple, STR (G) corresponds to the STR __ .__ G () 

# 2. __repr__ methods: a method __str__ the spare tire, when the class is not __str__ methods, still can call __str__ method. 
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__ method corresponding to 

# 4. The method of the __del__: 
class Goods:
     DEF  the __del__ (Self):
         Print ( ' delete item ' ) 
Apple = Goods ()
 del apple # remove items, first call __del__ method, print out the 'delete item', then delete the apple object. 
Print (Apple) # name 'Apple' IS Not defined 

class A:
     DEF  the __del__ (Self): # destructor: deleting an object is performed before finishing 
        self.f.close () 
A = A () 
AF = Open ( ) #af operator then get a file stored in memory, open () to open the file 
del A # del first implementation method, after removing A 

# 5. The method of the __call__: obj () can call this method. 
class Goods:
     DEF  the __call__ (Self):
         Print ( ' calling method ' ) 
Apple = Goods () 
Apple () # call method

 

Guess you like

Origin www.cnblogs.com/python-daxiong/p/11242592.html