假设我有一个文件“icon.ico”和一个url“url.com”。
只在类中使用一次-“icon.ico”将设置为某个窗口,我们将用一种方法请求url。
我有三种方法来定义这些变量。
第1种方式-定义为全局常量
#in the top of the file
ICON = "icon.ico"
URL = "http://url.com"
#and then
def setIcon(self):
self.setWindowIcon(QtGui.QIcon(ICON))
def getData(self):
content = requests.get(URL).content
第二种方式-定义为类的变量
def __init__(self):
self.url = "http://url.com"
self.icon = "icon.ico"
第三方-仅在将要使用的方法内定义
def setIcon(self):
icon = "icon.ico"
def getData(self):
url = "http://url.com"
经验法则
而不是:
或者
更喜欢:
或者,如果您认为这些值将是相同的90%:
何时使用每个案例的提示
第1种方式-定义为全局常量
第二种方式-定义为类的变量
第三方-仅在将要使用的方法内定义
4路-作为类级常量
将它们定义为类变量可能是最有前途的方法,因为您以后可以使用dependency injection来更改这些变量,这对unit testing非常有用。例如:
关于接二连三的注记:
还要注意的是,在Python中,getter和setter倾向于避免使用,如果需要验证,则使用properties代替,或者重构具有大量依赖代码的类。在Java和C等预编译语言中,getter/setter用于封装,以便以后可以更改实现,但在Python中,为了提高性能和清晰度,避免使用getter/setter。因此,首先,变量可以正常访问,如果实现发生更改,那么可以使用
@property
和@variable.setter
修饰符,以便使用getter和setter,即使您看起来是直接访问变量。因此,最初您可以直接访问
icon
。但让我们说,稍后重构类中的
icon
为_icon_file
和_icon_image
,并在每次设置时加载文件,但应用程序的其余部分需要icon
变量。这就是getter和setter通常的用途(以及对设置变量的任何检查/转换),因此我们现在可以为icon
添加getter和setter,即使icon
变量不再存在:您忘记了将它们定义为类级常量的选项:
相关问题 更多 >
编程相关推荐