初学者,idomatic python 2 [英] beginner, idomatic python 2
问题描述
有人想建议更换吗?这是一个
函数,可以返回不同类型的相似对象,具体取决于要求的
。 PSP和PWR是类。我不是真的想要重新编写调用代码:我只是想知道
如果函数可以用某种OOP替换模式。
def设备(DeviceType):
如果DeviceType ==''PSP'':
返回PSP()
elif DeviceType ==电源
返回PWR()
等...
谢谢!
Would someone like to suggest a replacement for this? This is a
function that returns different kinds of similar objects, depending
on what is asked for. PSP and PWR are classes. I don''t really
want to re-write the calling code very much: I''m just wondering
if the function can be replaced with some kind of OOP pattern.
def Device(DeviceType):
if DeviceType==''PSP'':
return PSP()
elif DeviceType=="Power Supply"
return PWR()
etc...
Thanks!
推荐答案
8月23日晚上10点21分,bambam < da ... @ asdf.asdfwrote:
On Aug 23, 10:21 pm, "bambam" <da...@asdf.asdfwrote:
有人想建议替换吗?这是一个
函数,可以返回不同类型的相似对象,具体取决于要求的
。 PSP和PWR是类。我不是真的想要重新编写调用代码:我只是想知道
如果函数可以用某种OOP替换模式。
def设备(DeviceType):
如果DeviceType ==''PSP'':
返回PSP()
elif DeviceType ==电源
返回PWR()
等...
谢谢!
Would someone like to suggest a replacement for this? This is a
function that returns different kinds of similar objects, depending
on what is asked for. PSP and PWR are classes. I don''t really
want to re-write the calling code very much: I''m just wondering
if the function can be replaced with some kind of OOP pattern.
def Device(DeviceType):
if DeviceType==''PSP'':
return PSP()
elif DeviceType=="Power Supply"
return PWR()
etc...
Thanks!
通常,你会使用字典:
DEVICE_DICT = {
' 'PSP'':PSP。
''电源'':PWR,
#等
}
,你的函数只返回DEVICE_DICT [device_type]()
Typically, you''d use a dictionary:
DEVICE_DICT = {
''PSP'': PSP.
''Power Supply'': PWR,
# etc.
}
and your function would simply return DEVICE_DICT[device_type]()
bambamaécrit:
bambam a écrit :
有人想建议替换吗?这是一个
函数,可以返回不同类型的相似对象,具体取决于要求的
。 PSP和PWR是类。我不是真的想要重新编写调用代码:我只是想知道
如果函数可以用某种OOP替换图案。
Would someone like to suggest a replacement for this? This is a
function that returns different kinds of similar objects, depending
on what is asked for. PSP and PWR are classes. I don''t really
want to re-write the calling code very much: I''m just wondering
if the function can be replaced with some kind of OOP pattern.
丹已经回答了这个问题。正如旁注,并且因为你试图成为惯用语,因此Python的命名惯例是使用all_lower
作为函数,MixedCaps对于课程(除了 - 主要是为历史
原因 - 内置类型...),以及ALL_LOWER为符号(伪)
常数。
>
def设备(DeviceType):
如果DeviceType ==''PSP'':
返回PSP()
elif DeviceType ==电源
返回PWR()
等...
谢谢!
def Device(DeviceType):
if DeviceType==''PSP'':
return PSP()
elif DeviceType=="Power Supply"
return PWR()
etc...
Thanks!
Bruno Desthuilliersaécrit:
(snip)
Bruno Desthuilliers a écrit :
(snip)
和ALL_LOWER
and ALL_LOWER
那是''ALL_UPPER'',当然:(
That''s ''ALL_UPPER'', of course :(
表示符号(伪)
常数。
for symbolic (pseudo)
constants.
这篇关于初学者,idomatic python 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!