我有一个python类,所有方法都是静态的,
class SomeClass:
@staticmethod
def somemethod(...):
pass
@staticmethod
def somemethod2(...):
pass
@staticmethod
def somemethod3(...):
pass
Run Code Online (Sandbox Code Playgroud)
这是正确的方法吗?
在reproduce方法ResistantVirus类,我试图调用reproduce(self, popDensity)的SimpleVirus类,但而不是返回SimpleVirus的对象,我希望它返回一个ResistantVirus对象。
显然,我也可以从SimpleVirus.reproduce方法中重复一些代码并在我的ResistantVirus.reproduce方法中使用相同的实现,但我想知道是否可以调用和覆盖SimpleVirus.reproduce以避免重复?
class SimpleVirus(object):
def __init__(self, maxBirthProb, clearProb):
self.maxBirthProb = maxBirthProb
self.clearProb = clearProb
def reproduce(self, popDensity):
if random.random() > self.maxBirthProb * (1 - popDensity):
raise NoChildException('In reproduce()')
return SimpleVirus(self.getMaxBirthProb(), self.getClearProb())
class ResistantVirus(SimpleVirus):
def __init__(self, maxBirthProb, clearProb, resistances, mutProb):
SimpleVirus.__init__(self, maxBirthProb, clearProb)
self.resistances = resistances
self.mutProb = mutProb
def reproduce(self, popDensity)
## returns a new instance of the ResistantVirus class representing …Run Code Online (Sandbox Code Playgroud) 如果这是一个重复的问题我很抱歉,但我找不到任何类似的例子,所以寻求你的帮助.
lookup = {}
# These values will be filled by DB lookup service at runtime
# Maximum array length for category is unknown before program start
# Format [Lookup Category], [Lookup Key], Lookup Id
lookup['name']['John'] = 1
lookup['name']['Jane'] = 2
lookup['name']['Joe'] = 3
lookup['gender']['Male'] = 1
lookup['gender']['Female'] = 2
lookup['country']['Japan'] = "jp"
lookup['country']['China'] = "ch"
print lookup['name']['Jane']
print lookup['gender']['Female']
print lookup['country']['China']
Run Code Online (Sandbox Code Playgroud) 假设我有一个变量 a,其中有一个列表,它看起来像这样:
a = ['hello', 'there']
Run Code Online (Sandbox Code Playgroud)
我想解压列表,但我不想使用 for 循环,但我只是不知道如何使其工作。我试过了:
def unpack(table):
for i in table:
return i
a = ['hello', 'there']
print(unpack(a))
Run Code Online (Sandbox Code Playgroud)
我想要打印它
hello, there
Run Code Online (Sandbox Code Playgroud)
但它只打印 hello 有人可以帮我吗?
但它只返回你好
我想出了这段代码,将已排序的整数列表转换为连续正整数列表。
def consecutive_positive_inc(l):
"""
[0, 1, 1, 3, 4, 4, 5] -> [0, 1, 1, 2, 3, 3, 4]
"""
from collections import defaultdict
d = defaultdict(int)
for i in l:
d[i] += 1
for i, count in enumerate(d.values()):
for _ in range(count):
yield i
if __name__ == '__main__':
l = [-3, -2, -1, 0, 1, 1, 3, 4, 4, 5]
result = list(consecutive_positive_inc(l))
assert result == [0, 1, 2, 3, 4, 4, 5, 6, 6, 7]
Run Code Online (Sandbox Code Playgroud)
这是最好的方法还是可以使用更简单的方法?