Custom Input Instance name output
def __str__ will customize the output of the output instance name
class Chain(object): def __str__(self): return "hello"c = Chain()print(c) #本来是<__main__.Chain object at 0x00000000021BE5C0># hello
Pass
def __str__
Output Property Name
class Chain(object): def __init__(self): self.name = "maotai" def __str__(self): return self.namec = Chain()print(c)# maotai
__getattr__
Print any property, such as C.xx,c.yy
The main purpose is to implement dynamic add properties
class Chain(object): # 打印c.xx属性 def __getattr__(self, item): return itemc = Chain()print(c.xx)#xxx
class Chain(object): def __init__(self): self.name = "maotai" # 打印c.xx属性时候返回定制内容 def __getattr__(self, item): return item, self.namec = Chain()print(c.xx)# ('xx', 'maotai')
Profiling Print Results
class Chain(object): def __init__(self, path=""): self.__path = path def __str__(self): return self.__path ## 打印Chain()的内容 def __getattr__(self, item): # Chain("%s/%s" % (self.__path, item))即 __str__的结果 return Chain("%s/%s" % (self.__path, item)) ## 打印c.xx时, 返回Chain()的内容c = Chain()#c.xx 的结果 Chain("/xx")print(c.xx)
class Chain(object): def __init__(self, path=""): self.__path = path print(self.__path, "++++") def __str__(self): # print(self.__path,"--------") return self.__path ## 打印Chain()的内容 def __getattr__(self, item): # Chain("%s/%s" % (self.__path, item))获取到的是 self.__path内容,供__getattr__返回. # self.__path的内容是 ("%s/%s" % (self.__path, item)) # 第1次 self.__path="/xx", 供__getattr__返回. # 第2次 self.__path="/xx/yy",供__getattr__返回. # 第3次 self.__path="/xx/zz",供__getattr__返回. # return Chain() # return Chain("/xx") # return Chain("/xx/yy") # return Chain("/xx/yy/zz") return Chain("%s" % (item)) ## 打印c.xx时, 返回Chain()的内容c = Chain()#c.xx 的结果 Chain("/xx")#c.xx.yy 的结果 Chain("/xx/yy")#c.xx.yy.zz 的结果 Chain("/xx/yy/zz")print(c.xx.yy.zz)# /xx/yy/zz
[Py]python str GetAttr Special method