小编Jim*_*ard的帖子

使用类作为其方法中的参数的类型提示

我在下面包含的代码会引发以下错误:

NameError: name 'Vector2' is not defined 
Run Code Online (Sandbox Code Playgroud)

在这一行:

def Translate (self, pos: Vector2):
Run Code Online (Sandbox Code Playgroud)

为什么Python不能Vector2Translate方法中识别我的类?

class Vector2:

    def __init__(self, x: float, y: float):

        self.x = x
        self.y = y

    def Translate(self, pos: Vector2):

        self.x += pos.x
        self.y += pos.y
Run Code Online (Sandbox Code Playgroud)

python oop type-hinting python-3.x

16
推荐指数
2
解决办法
3188
查看次数

'{0}'.format()比使用IPython%timeit的str()和'{}'.format()更快,否则使用纯Python

所以它是一个CPython的东西,不太确定它与其他实现有相同的行为.

'{0}'.format()str()和更快'{}'.format().我发布了Python 3.5.2的结果,但是,我尝试使用Python 2.7.12并且趋势是相同的.

%timeit q=['{0}'.format(i) for i in range(100, 100000, 100)]
%timeit q=[str(i) for i in range(100, 100000, 100)]
%timeit q=['{}'.format(i) for i in range(100, 100000, 100)]

1000 loops, best of 3: 231 µs per loop
1000 loops, best of 3: 298 µs per loop
1000 loops, best of 3: 434 µs per loop
Run Code Online (Sandbox Code Playgroud)

文档object.__str__(self)

str(object)内置函数调用format()print()计算对象的"非正式"或可打印的字符串表示形式.

所以,str()format() …

python cpython

14
推荐指数
1
解决办法
1357
查看次数

为什么__self__的内置函数会返回它所属的内置模块?

方法有一个属性,__self__用于保存在调用基础函数时要传递的实例.显然,内置函数也是如此.

在Python 3中,它们包含模块对象:

>>> len.__self__
<module 'builtins' (built-in)>
>>> sys.getrefcount.__self__  # also for other builtin modules
<module 'sys' (built-in)>
Run Code Online (Sandbox Code Playgroud)

另一方面,在Python 2中,它们包含None:

>>> type(len.__self__)
<type 'NoneType'>
>>> sys.getrefcount.__self__
<type 'NoneType'>
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么这里有差异?除此之外,为什么这些甚至有一个__self__并且不像缺少__self__属性的Python级模块函数:

>>> from pprint import pprint
>>> pprint.__self__
AttributeError: 'function' object has no attribute '__self__'
Run Code Online (Sandbox Code Playgroud)

python python-2.7 python-3.x python-internals

14
推荐指数
1
解决办法
403
查看次数

为什么不能在f字符串中使用"await"?

为什么不能在f字符串中使用"await"?有没有办法强制f字符串在协程函数的上下文中评估格式表达式?

$ python3 
Python 3.6.0 (default, Mar  4 2017, 12:32:37) 
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> async def a(): return 1
... 
>>> async def b(): return 'The return value of await a() is {}.'.format(await a())
... 
>>> async def c(): return f'The return value of await a() is {await a()}'
... 
  File "<fstring>", line 1
    (await a())
           ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

python python-3.x python-3.6 f-string

14
推荐指数
1
解决办法
542
查看次数

如何更改Sublime Python注释颜色?

我真的很喜欢Monokai的颜色主题,除了一件事 - 我几乎看不到超过实际代码文本一半的注释.有没有办法专门改变评论的颜色,但根据monokai保留其余的?

python colors sublimetext sublimetext3

13
推荐指数
4
解决办法
9519
查看次数

ImageFont IO错误:无法打开资源

我是Python的新手,并尝试运行以下代码.我收到以下错误"IOError: cannot open resource".这是因为某些图像特征不再存在(例如Coval.otf),还是由于写入/读取限制?请让我知道 - 非常感谢,W

import numpy as np
from PIL import Image, ImageDraw, ImageFont
from skimage import transform as tf

def create_captcha(text, shear=0, size=(100,24)):
    im = Image.new("L", size, "black")
    draw = ImageDraw.Draw(im)
    font = ImageFont.truetype(r"Coval.otf", 22)
    draw.text((2, 2), text, fill=1, font=font)
    image = np.array(im)
    affine_tf = tf.AffineTransform(shear=shear)
    image = tf.warp(image, affine_tf)
    return image / image.max()

%matplotlib inline
from matplotlib import pyplot as plt
image = create_captcha("GENE", shear=0.5)
Run Code Online (Sandbox Code Playgroud)

python io python-imaging-library

13
推荐指数
3
解决办法
2万
查看次数

Python 3.5+中的递归键入

在Python 3.5中,添加了类型注释(参见此处).

有没有一种定义递归类型注释的方法,例如树状结构?

class Employee(object):
    def __init__(self, name: str, reports: List[Employee]):
       self.name = name
       self.reports = reports
Run Code Online (Sandbox Code Playgroud)

在上面,似乎注释不起作用List[Employee].运行代码会导致此错误:

NameError: name 'Employee' is not defined

python recursion type-hinting python-3.x

13
推荐指数
1
解决办法
3569
查看次数

函数描述符如何工作?

当我在一张幻灯片(数字)中断言Pythons的函数是描述符时,我正在阅读关于Pythons的对象模型的演示文稿9.他提出的例子类似于我写的这个例子:

def mul(x, y):
    return x * y

mul2 = mul.__get__(2)
mul2(3) # 6
Run Code Online (Sandbox Code Playgroud)

现在,我明白了这一点,因为函数定义了__get__它是一个描述符,正如我在Python文档的描述部分中所描述的那样.

我不明白的是,调用是如何产生输出的.

python function descriptor python-2.7 python-3.x

13
推荐指数
1
解决办法
880
查看次数

为什么1 // 0.1 == 9.0?

在Python 2.73.x,为什么整数除法给我一个不正确的数量由数除以时0 < x < 1

负数-1 < x < 0甚至可以正常工作:

>>> 1//.1
9.0
>>> 1//-.1
-10.0
Run Code Online (Sandbox Code Playgroud)

我理解带负数(或正数)的整数除法向负无穷大舍入,但我认为1//.1应该导致10.0因为1可以除以.1余数.

python floating-point integer-division

13
推荐指数
1
解决办法
1240
查看次数

为什么在Python 3.6中评估f"\ {10}"时符号"{"仍然存在?

f-string是Python 3.6中的新功能之一.

但是,当我尝试这个:

>>> f"\{10}"
'\\{10'
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚为什么左大括号'{'保留在结果中.我认为结果应该与str.format:

>>> "\{}".format(10)
'\\10'
Run Code Online (Sandbox Code Playgroud)

PEP-0498中,它没有明确回答这个问题.那么是什么原因导致左大括号'{'留在结果和是什么原因导致之间的差异f-stringstr.format()

python python-3.x python-3.6 f-string

13
推荐指数
1
解决办法
390
查看次数