如果我有一个对象,并且在该对象中我已经定义了一个变量,那么这些方法中哪一个被认为是"最好的"来访问变量?
方法一
使用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 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.
我需要将位于内存中的OpenCV映像写入BytesIO或Tempfile对象,以在其他地方使用。
就我个人来说,这是一个死胡同的问题,因为cv2.imwrite()需要一个文件名作为参数,然后使用文件扩展名来推断图像类型来写(.jpg,.png,.tiff等)。cv2.imwrite()在C ++级别执行此操作,因此我担心无法成功将非文件名对象传递给它。
另一种可能的解决方案是转换为PILthrough numpy,它具有写入BytesIO和Tempfile对象的能力,但是我想避免不必要的复制。