小编Chr*_*lan的帖子

哪些是访问类中变量的最佳实践?

如果我有一个对象,并且在该对象中我已经定义了一个变量,那么这些方法中哪一个被认为是"最好的"来访问变量?

方法一

使用getter函数

class MyClass:
    def __init__(self):
        self.the_variable = 21 * 2

    def get_the_variable(self):
        return self.the_variable

if __name__ == "__main__"
    a = MyClass()
    print(a.get_the_variable())
Run Code Online (Sandbox Code Playgroud)

方法二

使用@property装饰器

class MyClass:

    def __init__(self):
        self._the_variable = 21 * 2

    @property
    def the_variable(self):
        return self._the_variable

if __name__ == "__main__"
    a = MyClass()
    print(a.the_variable)
Run Code Online (Sandbox Code Playgroud)

方法三

只需直接访问它

class MyClass:
    def __init__(self):
        self.the_variable = 21 * 2

if __name__ == "__main__"
    a = MyClass()
    print(a.the_variable)
Run Code Online (Sandbox Code Playgroud)

这些方法中的任何一种都比其他方法更加pythonic吗?

python python-3.x

6
推荐指数
1
解决办法
103
查看次数

如何将参数传递给 Python 3 中的自定义静态类型提示?

我是 Python 3 中的静态类型提示的忠实粉丝和拥护者。我已经使用它们一段时间了,没有任何问题。

我刚刚遇到了一个我似乎无法编译的新边缘案例。如果我想定义一个自定义类型,然后定义它的参数怎么办?

例如,这在 Python 3 中很常见:

from typing import List, NewType
CustomObject = NewType('CustomObject', List[int])

def f(data: List[CustomObject]):
    # do something
Run Code Online (Sandbox Code Playgroud)

但这不会编译:

class MyContainer():
    # some class definition ...

from typing import NewType
SpecialContainer = NewType('SpecialContainer', MyContainer)

def f(data: SpecialContainer[str]):
    # do something
Run Code Online (Sandbox Code Playgroud)

我意识到SpecialContainer在这种情况下这在技​​术上是一个函数,但它不应该在类型签名的上下文中被评估为一个函数。第二个代码片段失败,TypeError: 'function' object is not subscriptable.

python python-3.x python-3.5 python-3.6 python-typing

5
推荐指数
1
解决办法
1241
查看次数

将内存中的OpenCV映像写入BytesIO或Tempfile

我需要将位于内存中的OpenCV映像写入BytesIO或Tempfile对象,以在其他地方使用。

就我个人来说,这是一个死胡同的问题,因为cv2.imwrite()需要一个文件名作为参数,然后使用文件扩展名来推断图像类型来写(.jpg.png.tiff等)。cv2.imwrite()在C ++级别执行此操作,因此我担心无法成功将非文件名对象传递给它。

另一种可能的解决方案是转换为PILthrough numpy,它具有写入BytesIOTempfile对象的能力,但是我想避免不必要的复制。

python opencv

2
推荐指数
1
解决办法
2940
查看次数