[py]python面向对象的str getattr特殊方法

本文旨在说清楚 类中的

  • def init
  • def str
  • def getattr

这三个方法怎么用的.

定制输入实例名时输出内容

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
原文地址:https://www.cnblogs.com/iiiiiher/p/8325617.html