我有这门课:
class ReallyLongClassName:
static_var = 5
def instance_method(self):
ReallyLongClassName.static_var += 1
Run Code Online (Sandbox Code Playgroud)
有没有办法使用自变量访问静态变量?我宁愿做类似的事情class(self).static_var += 1,因为长名字是不可读的.
我刚做了一个有趣的测试:
~$ python3 # I also conducted this on python 2.7.6, with the same result
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo(object):
... def __add__(self, other):
... global add_calls
... add_calls += 1
... return Foo()
... def __iadd__(self, other):
... return self
...
>>> add_calls = 0
>>> a = list(map(lambda x:Foo(), range(6)))
>>> a[0] + a[1] + a[2]
<__main__.Foo object at 0x7fb588e6c400> …Run Code Online (Sandbox Code Playgroud) 所以我有一个界面:
interface IFoo
{
int Bar();
int this[int i] {get; set;}
}
Run Code Online (Sandbox Code Playgroud)
还有一个源自它的类
class Foo : IFoo
{
public int IFoo.Bar()
{
//Implementation
{
public int IFoo.this[int i]
{
//Implementation
}
}
Run Code Online (Sandbox Code Playgroud)
现在,我尝试这样做:
var fooey = new Foo();
int i = Fooey.Bar();
Run Code Online (Sandbox Code Playgroud)
或这个:
int i = Fooey[4];
Run Code Online (Sandbox Code Playgroud)
我希望这些能够正常运作.但是,编译器会生成错误,就好像这些成员不存在一样.这是为什么?我知道我可以演员Foo as IFoo,但我也知道演员表演成本很高,这通常是首先使用界面的原因.
编辑1:这些是生成的错误
'Foo'不包含'Bar'的定义,并且没有扩展方法'Bar'可以找到接受类型'Foo'的第一个参数(你是否缺少using指令或汇编引用?)
"无法将索引应用于'Foo'类型的表达式"
我们有一些看起来像这样的代码:
from third_party_library import foo
for n in range(3):
try:
foo(args)
break
except:
print "Retry %i / 3" % n
Run Code Online (Sandbox Code Playgroud)
我想使用一个装饰器,让我们的代码更加简洁,看起来像这样:
from third_party_library import foo
@retry(3)
foo(args)
Run Code Online (Sandbox Code Playgroud)
这给出了语法错误.我错过了什么,或者python是否只允许装饰器使用语句?
我有以下三个类:
class foo(object):
pass
class bar(foo):
pass
class baz(bar):
pass
Run Code Online (Sandbox Code Playgroud)
我想要一个像这样的方法:
>>> class_stack(baz)
baz > bar > foo
Run Code Online (Sandbox Code Playgroud)