给定一个具有一些受保护成员的类,并通过一个公共接口对其进行修改,通常什么时候可以直接访问受保护成员?我想到了一些具体的例子:
我不想公开这些属性,因为我不想公开地触摸它们。我的语法IDE语法高亮显示,我在访问受保护的成员时错了-谁在这里?
编辑 -在下面添加一个简单的示例:
class Complex:
def __init__(self, imaginary, base):
self._imaginary = imaginary
self._base = base
def __str__(self):
return "%fi + %f" % self._base, self._imaginary
def __add__(self, other):
return Complex(self._imaginary + other._imaginary, self._base + other._base)
Run Code Online (Sandbox Code Playgroud)
Pycharm 使用以下内容突出显示other._imaginary和other._base:
访问类的受保护成员_imaginary
我有一个简单的函数定义如下:
allZero :: Num a => [a]-> Bool
allZero [] = False
allZero xs = and (map (== 0) xs)
Run Code Online (Sandbox Code Playgroud)
这会在加载时返回错误消息:
无法推断(Num a)由字面值"0"引起
这个功能有什么问题?如何将数字0过载为任何数字类型?
我有一个字符串,我想在特定位置将其拆分为字符串列表。分割点存储在单独的分割列表中。例如:
test_string = "thequickbrownfoxjumpsoverthelazydog"
split_points = [0, 3, 8, 13, 16, 21, 25, 28, 32]
Run Code Online (Sandbox Code Playgroud)
...应该返回:
>>> ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经把这个作为解决方案,但对于任务的简单性来说,它看起来非常复杂:
split_points.append(len(test_string))
print [test_string[start_token:end_token] for start_token, end_token in [(split_points[i], split_points[i+1]) for i in xrange(len(split_points)-1)]]
Run Code Online (Sandbox Code Playgroud)
有什么好的字符串函数可以完成这项工作,还是这是最简单的方法?
提前致谢!
通过示例解释最简单:
events = ['foo', 'bar', 'biz', 'foo', 'foo']
events_counter = {}
for event in events:
if event not in events_counter: # {
events_counter[event] = 1 # {
else: # {
events_counter[event] += 1 # {
print events_counter
# {'biz': 1, 'foo': 3, 'bar': 1}
Run Code Online (Sandbox Code Playgroud)
有没有办法以更加pythonic的方式实现突出显示的代码?我觉得应该有一个内置函数,即:
events_counter.count_up(event)
Run Code Online (Sandbox Code Playgroud)
是的,我知道我可以写自己的程序,谢谢.
python ×3
attributes ×1
counter ×1
dictionary ×1
haskell ×1
oop ×1
overloading ×1
polymorphism ×1
protected ×1
split ×1
string ×1