在实例方法中指向类方法显然会导致问题:
class A(dict):
def __getitem__(self, name):
return dict.__getitem__(self, name)
class B(object):
def __init__(self):
self.a = A()
B.__getitem__ = self.a.__getitem__
b1 = B()
b1.a['a'] = 5
b2 = B()
b2.a['b'] = 10
c = b1['a']
d = b2['b']
Run Code Online (Sandbox Code Playgroud)
给出了这个错误:
File ... in __getitem__
return dict.__getitem__(self, name)
KeyError: 'a'
Run Code Online (Sandbox Code Playgroud)
我应该在这做什么呢?
有人能解释为什么Python会做以下事情吗?
>>> class Foo(object):
... bar = []
...
>>> a = Foo()
>>> b = Foo()
>>> a.bar.append(1)
>>> b.bar
[1]
>>> a.bar = 1
>>> a.bar
1
>>> b.bar
[1]
>>> a.bar = []
>>> a.bar
[]
>>> b.bar
[1]
>>> del a.bar
>>> a.bar
[1]
Run Code Online (Sandbox Code Playgroud)
这让人很困惑!
在python 3中,我发现class属性可以在__init__()函数中用作参数,如下所示:
file test.py:
class Foo:
var1 = 23333
def __init__(self, var=var1):
self.var = var
Run Code Online (Sandbox Code Playgroud)
在cmd中运行:
C:\Users\rikka\Desktop>py -3 -i test.py
>>> f1=Foo()
>>> f1.var
23333
Run Code Online (Sandbox Code Playgroud)
但是通过使用dot.expression,当init这个类时,解释器将报告错误:
文件test2.py:
class Foo:
var1 = 23333
def __init__(self, var=Foo.var1):
self.var = var
Run Code Online (Sandbox Code Playgroud)
在cmd中运行:
C:\Users\rikka\Desktop>py -3 -i test2.py
Traceback (most recent call last):
File "test2.py", line 1, in <module>
class Foo:
File "test2.py", line 3, in Foo
def __init__(self, var=Foo.var1):
NameError: name 'Foo' is not defined
Run Code Online (Sandbox Code Playgroud)
我只是不知道为什么解释器找不到名字'Foo',因为Foo是环境中全局框架中的名字.有什么关于python类的范围相关的概念,我不完全理解?
在Python我们可以将属性添加到一个对象(类)动态地,例如:
class Foo(object):
pass
foo = Foo()
foo.a = 10
Run Code Online (Sandbox Code Playgroud)
我的问题可能有点理论上的问题.所以,它很方便.但是我们为什么要使用这个功能??? 当这种方法更可取时,有什么特别的情况吗?封装怎么样?