确定变量是否在Python中定义[重复]

本文翻译自:Determine if variable is defined in Python [duplicate]

Possible Duplicate: 可能重复:
Easy way to check that variable is defined in python? 在python中定义检查变量的简单方法?
How do I check if a variable exists in Python? 如何检查Python中是否存在变量?

How do you know whether a variable has been set at a particular place in the code at runtime? 您如何知道变量是否已在运行时在代码中的特定位置设置? This is not always obvious because (1) the variable could be conditionally set, and (2) the variable could be conditionally deleted. 这并不总是显而易见的,因为(1)变量可以有条件地设置,(2)变量可以有条件地删除。 I'm looking for something like defined() in Perl or isset() in PHP or defined? 我正在寻找像Perl中的defined()或PHP中的isset()defined? in Ruby. 在Ruby中。

if condition:
    a = 42

# is "a" defined here?

if other_condition:
    del a

# is "a" defined here?

#1楼

参考:https://stackoom.com/question/6gIX/确定变量是否在Python中定义-重复


#2楼

try:
    a # does a exist in the current namespace
except NameError:
    a = 10 # nope

#3楼

try:
    thevariable
except NameError:
    print("well, it WASN'T defined after all!")
else:
    print("sure, it was defined.")

#4楼

'a' in vars() or 'a' in globals()

如果你想变得迂腐,你也可以查看内置的
'a' in vars(__builtins__)


#5楼

I think it's better to avoid the situation. 我认为最好避免这种情况。 It's cleaner and clearer to write: 写起来更清晰,更清晰:

a = None
if condition:
    a = 42

#6楼

For this particular case it's better to do a = None instead of del a . 对于这种特殊情况,最好做a = None而不是del a This will decrement reference count to object a was (if any) assigned to and won't fail when a is not defined. 这将减少对象a引用计数(如果有的话),并且在未定义a时将不会失败。 Note, that del statement doesn't call destructor of an object directly, but unbind it from variable. 注意, del语句不直接调用对象的析构函数,而是从变量中解除绑定。 Destructor of object is called when reference count became zero. 当引用计数变为零时,将调用对象的析构函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值