[py]python str getattr特殊方法
阿新 • • 發佈:2018-01-22
sel 返回 pos getattr object log ota __str__ 通過 通過
定制輸入實例名時輸出
def __str__會定制輸出實例名時候的輸出
class Chain(object):
def __str__(self):
return "hello"
c = Chain()
print(c) #本來是<__main__.Chain object at 0x00000000021BE5C0>
# hello
通過def __str__
輸出屬性名
class Chain(object): def __init__(self): self.name = "maotai" def __str__(self): return self.name c = Chain() print(c) # maotai
__getattr__
打印任意屬性,如c.xx,c.yy
主要目的是實現動態添加屬性
class Chain(object):
# 打印c.xx屬性
def __getattr__(self, item):
return item
c = Chain()
print(c.xx)
#xxx
class Chain(object): def __init__(self): self.name = "maotai" # 打印c.xx屬性時候返回定制內容 def __getattr__(self, item): return item, self.name c = Chain() print(c.xx) # ('xx', 'maotai')
剖析打印結果
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特殊方法