Tag: python decorators

如何避免“self.x = x; self.y = y; __init__中的self.z = z“模式?

我看到类似的模式 def __init__(self, x, y, z): … self.x = x self.y = y self.z = z … 相当频繁,往往有更多的参数。 有没有避免这种乏味的重复性的好方法? 该类应该从namedtupleinheritance吗?

关于如何在python中使用属性function的真实世界的例子?

我感兴趣的是如何在Python中使用@property 。 我读过python文档和那里的例子,在我看来,只是一个玩具代码: class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x 我不知道从包装属性装饰器的_x可以得到什么好处。 为什么不只是实现为: class C(object): def __init__(self): self.x = None 我认为,在某些情况下,属性function可能会有用。 但当? 有人能给我一些真实的例子吗? 谢谢。

@property装饰器是如何工作的?

我想了解内置的函数property如何工作。 令我困扰的是,这个property也可以作为装饰器使用,但是当它作为一个内置函数使用时,它仅仅需要参数,而不能当作装饰器使用。 这个例子来自文档 : class C(object): def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") property的参数是getx , setx , delx和一个文档string。 在下面的代码中, property被用作装饰器。 它的对象是x函数,但在上面的代码中,参数中没有对象函数的地方。 class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' […]