Python 类中的Java样式变量声明

Python 类中的Java样式变量声明,python,coding-style,variable-declaration,Python,Coding Style,Variable Declaration,我试图理解Python OOP中的最佳实践 我非常熟悉Java风格的工作流: 属性声明 属性实例化 我喜欢它的地方在于,在我看来,它提高了可读性:通过简短地查看属性,您可以确切地知道将在类中使用哪些属性 我希望在Python中获得相同的结果,虽然我知道Python中没有“变量声明”这样的东西,但可能有某种设计模式允许这样做 到目前为止,我的中间解决方案是在\uuuu init\uuuu方法中进行“声明”,包括: def __init__(self): self.attribute1 =

我试图理解Python OOP中的最佳实践

我非常熟悉Java风格的工作流:

  • 属性声明
  • 属性实例化
  • 我喜欢它的地方在于,在我看来,它提高了可读性:通过简短地查看属性,您可以确切地知道将在类中使用哪些属性

    我希望在Python中获得相同的结果,虽然我知道Python中没有“变量声明”这样的东西,但可能有某种设计模式允许这样做

    到目前为止,我的中间解决方案是在
    \uuuu init\uuuu
    方法中进行“声明”,包括:

    def __init__(self):
        self.attribute1 = None
        self.attribute2 = None 
    
    并在随后的方法中实例化这些元素。
    但我觉得它相当难看,我很高兴听到一个更优雅的模式。

    声明输入的最佳位置是在类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
    
    当有人调用
    help(Foo)
    时,将打印文档字符串。这将被实例化和引用:

    help(Foo)
    my_foo = Foo('bar', ('baz', 42))
    help(my_foo)
    

    请注意,由于我们为属性提供了默认值None,因此我们可以在没有给定属性的情况下实例化对象,并在稍后使用
    is None
    检查它们的实例化。声明输入的最佳位置是在类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
    
    当有人调用
    help(Foo)
    时,将打印文档字符串。这将被实例化和引用:

    help(Foo)
    my_foo = Foo('bar', ('baz', 42))
    help(my_foo)
    

    请注意,由于我们为属性提供了默认值None,因此我们可以在没有给定属性的情况下实例化对象,并在Python 3.x中使用
    is None
    检查其实例化,您可以使用添加参数元数据和返回值:

    class Demo():
    
        def __init__(self, attribute1: str, attribute2: "int - number of foos" = 0):
            self.attribute1 = attribute1
            self.attribute2 = attribute2
    
        def foo(self) -> int:
            return self.attribute2
    

    它们不是强制执行的(没有第三方库),但确实为类的用户提供了有用的信息(例如,在IDE中显示为工具提示以及在
    help(Demo)
    提供的信息中)。在Python 3.x中,您可以使用添加参数元数据和返回值:

    class Demo():
    
        def __init__(self, attribute1: str, attribute2: "int - number of foos" = 0):
            self.attribute1 = attribute1
            self.attribute2 = attribute2
    
        def foo(self) -> int:
            return self.attribute2
    

    这些不是强制执行的(没有第三方库),但确实为类的用户提供了有用的信息(例如,在IDE中显示为工具提示以及在
    help(Demo)
    提供的信息中)。在类上设置属性使它们成为类属性,而不是实例属性。是的,非常感谢!请记住,您可以通过单击答案旁边的复选标记来接受,它将为您的代表提供+2:)在类上设置属性将使它们成为类属性,而不是实例属性。是的,非常感谢!请记住,您可以通过单击答案旁边的复选标记来接受,它将为您的代表提供+2:)这是一个很好的谷歌风格docstring示例。这是一个很好的谷歌风格docstring示例。