cyb*_*oac 0 python coding-style variable-declaration
我试图了解Python OOP中的最佳实践.
我非常熟悉Java风格的工作流程:
我喜欢它的是它在我看来提高了可读性:通过简短地查看属性,你就可以确切地知道你将在课堂上工作.
我想在Python中实现相同的结果,虽然我知道在Python中没有"变量声明"这样的东西,但也许某种设计模式可以做同样的事情.
到目前为止,我的中间解决方案是在__init__方法内部"声明" ,其中:
def __init__(self):
self.attribute1 = None
self.attribute2 = None
Run Code Online (Sandbox Code Playgroud)
并在后续方法中稍后实例化这些元素.但我发现它相当丑陋,我会很高兴听到一个更优雅的模式.
声明输入的最佳位置是在类docstring中:
class Foo(object):
'''
This class of object is instantiated with variables that are attributes:
attribute1 should be a string
attribute2 should be a tuple of length two for your parameters:
'''
def __init__(attribute1=None, attribute2=None):
self.attribute1 = attribute1
self.attribute2 = attribute2
Run Code Online (Sandbox Code Playgroud)
当有人打电话时help(Foo),将打印文档字符串.这将被实例化并引用:
help(Foo)
my_foo = Foo('bar', ('baz', 42))
help(my_foo)
Run Code Online (Sandbox Code Playgroud)
请注意,由于我们为属性提供了None的默认值,因此我们可以在没有给定属性的情况下实例化对象,并在以后检查它们的实例化is None.