[英]Which is more pythonic, factory as a function in a module, or as a method on the class it creates?
[英]When defining class attributes, which method of writing is more "Pythonic"?
我经常这样做,也许这是糟糕的设计,有更好的方法来做到这一点,但我从来没有遇到过任何问题。
在定义具有父对象的对象并将该对象的属性分配给父对象的属性时,这些编写方法中哪种更“Pythonic”?
假设我们正在做类似...
class SomeParent:
def __init__(self, value):
self.value = value
class SomeChild { ... }
parentObj = SomeParent(value="foo")
childObj = SomeChild(parent=parentObj)
为SomeChild
编写__init__
的“正确”方式是......
class SomeChild:
def __init__(self, parent):
self.parent = parent
self.value = parent.value
或者...
class SomeChild:
def __init__(self, parent):
self.parent = parent
self.value = self.parent.value
唯一的区别是在子对象上定义value
时使用self
。 显然,它们(似乎)工作方式完全相同,使用哪个重要吗? 还是我想多了?
您可以使用属性更干净地执行此操作:
class A:
def __init__(self, value):
self.value = value
class B:
def __init__(self, a):
self.a = a
@property
def value(self):
return self.a.value
assert B(A(2)).value == 2
这样, B.value
将自动更新为a.value
。
注意:我故意不使用暗示继承的名称“父”和“子”。 您没有使用继承。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.