将对象注入类实例

时间:2016-11-21 12:04:58

标签: python dependency-injection

我想知道在python 2.7或3.x中是否可以使用以下内容:

Class A:
    def inject(self, **args):
        ... do something ...

    def print(self):
        print(self.x)

x = np.ones(10)
a = A()
a.inject(x)
a.print()

请注意,我希望inject非常通用,并且能够将任何对象添加到类实例中。

你有什么想法?这是我想象的可能吗?

编辑:

我还想为注入的额外注入许多变量:

y = np.ones(10)
z = np.ones(10)
a.inject(y, z)

2 个答案:

答案 0 :(得分:1)

您可能需要使用"name" => preg_replace('/[\x00-\x1F\x80-\xFF]/', '', htmlspecialchars($configurationOptionName))

但是如果你想在setattr(a, "x", x)函数中使用这个调用,那么添加一个可以防止覆盖现有属性的检查可能会很有用 - 你可能想要使用inject(self, name, value)或类似的东西。如果没有这个检查,你有可能会在你意外覆盖属性后对你的对象发生什么事情感到非常惊讶。想象一下'偶然'if hasattr(self, name): raise AttributeError('attribute already exists');)

但是看看你的代码,你正在尝试使用类似'Python-with-classes'的东西,它看起来也像'java-ish'。在Python中,您不需要在类中定义a.inject("inject", x)inject()。你可以简单地写一下:

print()

我想阻止覆盖现有属性(即只允许第一次进样)并仍然是pythonic,定义你的类如下:

a = object()
x = 5
setattr(a, "x", x)
print(a.x)  # btw. how does your implementation `a.print()` in the question knows that attribute `x` exists?

然后你可以这样写:

class A(object):  # note the 'object' here, it is the 'new style' class
    def __setattr__(self, name, value):
        if hasattr(self, name):
            raise AttributeError("attribute '{}' already exists".format(name))
        object.__setattr__(self, name, value)

答案 1 :(得分:0)

如果我理解你的问题,那么你应该使用setattr

class A:
    def inject(self, name, value):
        setattr(self, name, value)

    def print(self):
        print(self.x)

x = [1, 1]
a = A()
a.inject('x', x)
a.print()
>> [1, 1]
相关问题