我只是试图测试:
if type(model_lines) == 'str':
turn into a list using split
Run Code Online (Sandbox Code Playgroud)
基于:
In [196]: type('a')
Out[196]: str
Run Code Online (Sandbox Code Playgroud)
然而,对于 x,一个字符串:
In [193]: if type(x) == 'str':
print 'string'
.....:
In [195]: if type(x) == type('a'):
print 'string'
.....:
string
Run Code Online (Sandbox Code Playgroud)
我很好奇为什么我不能使用这个输出来检查类型,它看起来更清晰,阅读速度更快。类型实际上返回什么不允许通过其返回显示进行检查?
我有一个字节的子类,提供了一个__getitem__dunder方法.该__getitem__方法始终在Python 3.5中调用,但仅在Python 2.7中调用非切片键.(相反,似乎父项__getitem__已应用于实例.)为什么这样,是否有解决方法?
class A(object):
def __getitem__(self, key):
print("in A.__getitem__ with key " + str(key))
return []
class B(bytes):
def __getitem__(self, key):
print("in B.__getitem__ with key " + str(key))
return []
if __name__ == "__main__":
import sys
print(sys.version)
a = A()
b = B()
print("[0]")
a[0]
b[0]
print("[0:1]")
a[0:1]
b[0:1]
print("[:1]")
a[:1]
b[:1]
Run Code Online (Sandbox Code Playgroud)
__getitem__始终调用类定义.
(venv) snafu$ python ./x.py
3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609]
[0]
in A.__getitem__ …Run Code Online (Sandbox Code Playgroud) 考虑这个例子,其中__dict__类的所有实例的 都A将指向全局 dict shared。
shared = {'a': 1, 'b': 2}
class A(object):
def __init__(self):
self.__dict__ = shared
Run Code Online (Sandbox Code Playgroud)
现在让我们测试一些事情:
>>> a = A()
>>> b = A()
>>> a.a, a.b, b.a, b.b
(1, 2, 1, 2)
>>> b.x = 100
>>> shared
{'a': 1, 'x': 100, 'b': 2}
>>> a.x
100
>>> c = A()
>>> c.a, c.b, c.x
(1, 2, 100)
>>> shared['foo'] = 'bar'
>>> a.foo, b.foo, c.foo
('bar', 'bar', 'bar')
>>> a.__dict__, b.__dict__, …Run Code Online (Sandbox Code Playgroud) testing on ../../test/test_patm.py
python: Python/compile.c:4420: int assemble_lnotab(struct assembler *,
struct instr *): Assertion `d_lineno >= 0' failed.
Aborted
Run Code Online (Sandbox Code Playgroud)
运行我的测试程序时,我收到了上面给出的错误.最后我发现Python3.5和Python3.6的源代码差别很小.只需一行:
Python3.5
static int
assemble_lnotab(struct assembler *a, struct instr *i)
{
int d_bytecode, d_lineno;
Py_ssize_t len;
unsigned char *lnotab;
d_bytecode = a->a_offset - a->a_lineno_off;
d_lineno = i->i_lineno - a->a_lineno;
assert(d_bytecode >= 0);
assert(d_lineno >= 0); // the only difference
if(d_bytecode == 0 && d_lineno == 0)
return 1;
...
Run Code Online (Sandbox Code Playgroud)
Python 3.6
static int
assemble_lnotab(struct assembler *a, struct instr *i)
{
int d_bytecode, …Run Code Online (Sandbox Code Playgroud) 我已经看到了一些Python元类使用super()调用的示例type.__init__()。这是做什么的?
例:
class Meta(type):
def __new__(cls, name, bases, dct):
dct['a']='a'
cls_obj = super(Meta, cls).__new__(cls, name, bases, dct)
return cls_obj
def __init__(cls_obj, name, bases, dct):
cls_obj.b = 'b'
dct['c'] = 'c'
#what does this do
super(Meta, cls_obj).__init__(name, bases, dct)
class Meta2(Meta):
def __init__(cls_obj, name, bases, dct):
cls_obj.b = 'b'
class Klass(metaclass=Meta):
pass
class Klass2(metaclass=Meta2):
pass
if __name__ == '__main__':
print(Klass.a)
print(Klass.b)
print(Klass.c)
Run Code Online (Sandbox Code Playgroud)
输出:
a
b
<...my system traceback...>
AttributeError: type object 'Klass' has no attribute 'c'
Run Code Online (Sandbox Code Playgroud)
显然 …
我知道 Python 中的变量实际上只是某些底层对象的引用/指针。由于它们是指针,我猜它们以某种方式“存储”或以其他方式与它们引用的对象的地址相关联。
这样的“地址存储”可能发生在 CPython 实现的较低级别。但我对 C 的了解还不足以从源代码中推断出这一点,我也不知道从源代码中的哪里开始查找。
所以,我的问题是:
在 CPython 的实现中,对象地址如何存储在指向它们的变量中,或者如何与指向它们的变量关联?
我正在将文件的每一行读入列表和字典,
with open("../data/title/pruned2_titleonly.txt", 'rb') as f_titles:
titles_lst = f_titles.read().split('\n')
assert titles_lst[-1] == ''
titles_lst.pop() # remove the last element, an empty string
titles_dict = {}
with open("../data/title/pruned2_titleonly.txt", 'rb') as f_titles:
for i,line in enumerate(f_titles):
titles_dict[i] = line
Run Code Online (Sandbox Code Playgroud)
我正在通过以随机顺序访问list/dict中的每个项目来测试性能:
n = len(titles_lst)
a = np.random.permutation(n)
%%time
for i in xrange(10):
t = []
for b in a:
t.append(titles_lst[b])
del t
>>> CPU times: user 18.2 s, sys: 60 ms, total: 18.2 s
>>> Wall time: 18.1 s
%%time
for i in …Run Code Online (Sandbox Code Playgroud) 我试着环顾四周,但我找不到任何关于这个话题的清楚.
是否在每次启动Python时自动导入的模块中实现内置函数?在哪个模块的情况下?
或者内置函数只是Python解释器中的嵌入式函数?
在python中,假设我们有以下列表:
my_list = ['a', 'b', 'c', 'd', ...]
会my_list.pop(3)比效率更高my_list.remove('d')吗?
is在Python中测试2个引用是否指向同一个对象.-5到256之间的数字在内部缓存,因此:
a = 10
b = 10
a is b # Results in True
Run Code Online (Sandbox Code Playgroud)
这是如何解释的:
20000 is 20000 # Results in True
Run Code Online (Sandbox Code Playgroud)
这两个数字都高于256. 2个整数不应该是2个不同的对象吗?
python ×10
python-internals ×10
python-2.7 ×3
python-3.x ×3
c ×2
class ×1
cpython ×1
dictionary ×1
int ×1
list ×1
literals ×1
metaclass ×1
performance ×1
python-3.5 ×1
runtime ×1
typechecking ×1