python占内存吗_在Python中,常量比变量占用更多的内存吗?

因为您使用的是python3.4,所以我建议用IntEnum替换所有的幻数。在

这将使您的代码更易于理解,并在必要时更易于修改。在

使用枚举的一个好处是,您不会像处理变量那样意外地更改它们的值。在

考虑这一准则import os

from hashlib import sha256

def compare(src, dest):

"""

Compare two files.

Arguments

src: Path of the source file.

dest: Path of the destination file.

Returns:

0 if source and destination are different

1 source and destination are identical

2 destination doesn't exist

3 source doesn't exist

"""

xsrc, xdest = os.path.exists(src), os.path.exists(dest)

if not xsrc:

return 3

if not xdest:

return 2

with open(src, 'rb') as s:

csrc = sha256(s.read()).digest()

if xdest:

with open(dest, 'rb') as d:

cdest = sha256(d.read()).digest()

else:

cdest = b''

if csrc == cdest:

return 1

return 2

这个代码本身并不清楚。它被记录下来。

但是一旦您尝试使用返回值,您就必须不断地引用文档。在

你能告诉我为什么下面的代码会这么做吗?如果没有参考compare的文档,就不能这样做。在

^{pr2}$

现在看看这个import os

from hashlib import sha256

from enum import IntEnum

class Cmp(IntEnum):

differ = 0 # source and destination are different

same = 1 # source and destination are identical

nodest = 2 # destination doesn't exist

nosrc = 3 # source doesn't exist

def compare(src, dest):

"""

Compare two files.

Arguments

src: Path of the source file.

dest: Path of the destination file.

Returns:

Cmp enum

"""

xsrc, xdest = os.path.exists(src), os.path.exists(dest)

if not xsrc:

return Cmp.nosrc

if not xdest:

return Cmp.nodest

with open(src, 'rb') as s:

csrc = sha256(s.read()).digest()

if xdest:

with open(dest, 'rb') as d:

cdest = sha256(d.read()).digest()

else:

cdest = b''

if csrc == cdest:

return Cmp.same

return Cmp.differ

所以如果你现在尝试使用它,它看起来像这样

^{4}$

您不需要参考compare的文档就可以理解这一点。您甚至不必检查Cmp枚举的细节。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值