假设我有一个文件“ icon.ico”和一个URL“ url.com”。
在类中将仅使用一次-“ icon.ico”将设置为某个窗口,我们将使用一种方法来请求url。
我有三种定义这些变量的方法。
第一种方法-定义为全局常数
#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"
第3种方法-在将要使用的方法中进行定义
def setIcon(self):
icon = "icon.ico"
def getData(self):
url = "http://url.com"
代替:
def __init__(self):
self.url = "http://url.com"
self.icon = "icon.ico"
要么
def setIcon(self):
icon = "icon.ico"
首选:
def __init__(self, url, icon):
self.url = url
self.icon = icon
或者,如果您认为这些值将保持90%相同:
def __init__(self, url="http://url.com", icon="icon.ico"):
self.url = url
self.icon = icon
第一种方法-定义为全局常数
第二种方式-定义为类的变量
第3种方法-在将要使用的方法中进行定义
第4种方式-作为类级别常量
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句