python的 __getattr__自动构建generator

在写某项目的时候,每次创建一个张量,都需要创建不同的符号来表示各个维度,于是参考代码的写法,打算写过symbol_generator。这就涉及python class的__getattr__

我查看了《python3 cookbook》全局搜索了__getattr__, 找到这一章的说明是8.15

class Symbol:
    def __init__(self,name):
        self.name=name
class Tensor:
    def __init__(self,syms):
        self.shape = syms
class SymbolGenerator:
    _symbols={}
    def __init__(self):
        pass
    def __enter__(self):
        return self
    def __exit__(self,*args):
        SymbolGenerator._symbols = {}
    def __getattr__(self,s_name):
        if s_name not in SymbolGenerator._symbols:
            SymbolGenerator._symbols[s_name]=Symbol(s_name)
        return SymbolGenerator._symbols[s_name]

然后就可以每次需要的时候得到这个符号了

s =SymbolGenerator()
x = Tensor([s.h,s.w,s.c])

方法是通过定义一个全局变量,每次第一次访问就创建它

猜你喜欢

转载自blog.csdn.net/Chunying27/article/details/128331322