存在变量 [英] Existance of of variable

查看:137
本文介绍了存在变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。我是Python的新手,并且无法弄清楚

如何检查变量是否存在。在下面的代码中我已经制作了

a kludge,但是我认为检查

最近是否存在并且不必在第一时间初始化它会更清楚。如何检查




以下代码找到最接近某个位置的地方并拒绝

这些地方也是如此很远。


dist = 1e9

最近= -1


for n,p in galaxy.places .iteritems():

dif = p.pos - pos

len = dif.len()

如果len< dist和len< 10.0 / self.zoom:

dist = len

最近= p


如果最近的话!= -1:

self.sel = [nearest.name]


如果你不介意,我还有一些其他问题需要解决。我是

将dist设置为1e9,因为这个值比任何一个星系中的任何一个位置都要大得多。是否有更好的方法来使用
初始化dist,这样就不可能失败?例如,

会将dist设置为无穷大工作,这是怎么做的?


扩展我的存在检查问题,如何检查什么类型

a变量有吗?


感谢您的帮助!


- Josiah

Hello. I am very new to Python, and have been unable to figure out how
to check if a variable exists or not. In the following code I have made
a kludge that works, but I think that it would be clearer to check if
closest exists and not have to initialize it in the first place. How is
that check done?

The following code finds the closest place to a position and rejects
places that are too far away.

dist = 1e9
closest = -1

for n,p in galaxy.places.iteritems():
dif = p.pos - pos
len = dif.len()
if len < dist and len < 10.0/self.zoom:
dist = len
closest = p

if closest != -1:
self.sel = [closest.name]

I also have a few other questions to tack on if you don''t mind. I am
setting dist to 1e9, because that is a larger value than any of the
places in the galaxy will be far away. Is there a better way to
initialize dist so that it is impossible for this to fail? For example,
would setting dist to infinity work, and how is that done?

Extending my existance checking question, how does one check what type
a variable has?

Thanks for your help!

-- Josiah

推荐答案

Josiah Manson写道:
Josiah Manson wrote:
你好。我是Python的新手,并且无法弄清楚如何检查变量是否存在。在下面的代码中,我已经制作了一个可行的kludge,但我认为检查
最近是否存在并且不必首先初始化它会更清楚。
检查完成了怎么办?


变量存储在两个字典中:globals()(用于全局

变量)和locals()(用于本地变量,也用于全局变量)

顶级)。


你可以这么写:


如果当地人最近( ):

self.sel = [nearest.name]

另一方面,如果你试图访问一个不存在的变量,

你会得到NameError异常。另一种方式是:


试试:

self.sel = [nearest.name]
除了NameError之外的


通过


如果你不介意,我还有一些其他问题需要解决。我是设置dist到1e9,因为这是一个比星系中任何一个地方都要远的地方。是否有更好的方法来初始化dist以使其不可能失败?例如,
会将dist设置为无限工作,这是如何完成的?


由字符串''inf''构成的浮点数,浮点数(''inf''),可以执行

技巧。但是我不知道细节。
Hello. I am very new to Python, and have been unable to figure out how
to check if a variable exists or not. In the following code I have made
a kludge that works, but I think that it would be clearer to check if
closest exists and not have to initialize it in the first place. How is
that check done?
Variables are stored in two dictionnaries: globals() (for global
variables) and locals() (for the local ones, which are also global on
top level).

You can therefore write:

if ''closest'' in locals():
self.sel = [closest.name]
On the other hand, if you try to access a variable which doesn''t exist,
you''ll get the NameError exception. Another way is then:

try:
self.sel = [closest.name]
except NameError:
pass

I also have a few other questions to tack on if you don''t mind. I am
setting dist to 1e9, because that is a larger value than any of the
places in the galaxy will be far away. Is there a better way to
initialize dist so that it is impossible for this to fail? For example,
would setting dist to infinity work, and how is that done?
The float constructed from the string ''inf'', float(''inf''), may do the
trick. I don''t know the details, though.
1e100< float(''inf'')
1e100 < float(''inf'')



True


扩展我的存在检查问题,如何检查变量的类型是什么?


True

Extending my existance checking question, how does one check what type
a variable has?




''__ class__''特殊属性[1]将返回该类。你可以

也看看内置''isinstance''[2]。


然而,类型检查不是python中常见的习惯用法,因为我们倾向于使用''duck typing''来表示:'如果你的对象可以用它做你想做的事,那就不要再花了b $ b b来检查它是否完全属于班级你期待。

因此我们经常尝试使用该对象然后捕获异常而不是检查对象然后使用它。


当然,有些情况下它不合适但是类型

检查在python中似乎不太常见。

[1] http://docs.python.org/lib/specialattrs.html

[2] http:// docs .python.org / lib / built-in-funcs.html


Josiah Manson写道:
Josiah Manson wrote:
你好。我是Python的新手,并且无法弄清楚如何检查变量是否存在。在下面的代码中我已经赚了


尝试:

变量

除了NameError:

#变量不存在

否则:

#变量存在


但实际上你很少需要这样做。

a kludge有效,但我认为检查
最近是否存在并且不必首先初始化它会更清楚。如何完成检查?

以下代码找到最接近某个位置的位置并拒绝距离太远的地方。

dist对于n,p = galaxy.places.iteritems():= = />

对于= = len()
如果len< dist和len< 10.0 / self.zoom:
dist = len
最近= p
如果最近的话!= -1:
self.sel = [nearest.name]


我更喜欢将变量设置为序列中的第一项,然后当我找到更好的时候,我会更新
更新。匹配:


如果galaxy.places:

pos = somewhere()

places = galaxy.places.itervalues()

最近= places.next()

nearest_dist =(nearest.pos - pos).len()

for p in places:

dist =(p.pos - pos).len()

如果dist< nearest_dist:

nearest_dist = dist

最近= p


如果nearest_dist< 10.0 / self.zoom:

self.sel = [nearest.name]


这很容易理解但是有一些冗余代码的缺点

('pos''和''其他地方''之间的距离在循环之前和循环中都计算了
。所以这里有一个使用min的替代方法( )

内置:


def dp(places,pos):

for i,p in enumerate(places):

yield(p.pos - pos).len(),i,p


如果galaxy.places:

pos =某处()

dist,_,place = min(dp(galaxy.places.itervalues(),pos))

if dist< 10.0 / self.zoom:

self.sel = [place.name]

扩展我的存在检查问题,如何检查变量的类型是什么?
Hello. I am very new to Python, and have been unable to figure out how
to check if a variable exists or not. In the following code I have made
try:
variable
except NameError:
# variable doesn''t exist
else:
# variable exists

But it is rare that you actually need to do that.
a kludge that works, but I think that it would be clearer to check if
closest exists and not have to initialize it in the first place. How is
that check done?

The following code finds the closest place to a position and rejects
places that are too far away.

dist = 1e9
closest = -1

for n,p in galaxy.places.iteritems():
dif = p.pos - pos
len = dif.len()
if len < dist and len < 10.0/self.zoom:
dist = len
closest = p

if closest != -1:
self.sel = [closest.name]
I prefer to set the variable to the first item in the sequence and later
update that when I find "better" matches:

if galaxy.places:
pos = somewhere()
places = galaxy.places.itervalues()
closest = places.next()
closest_dist = (closest.pos - pos).len()
for p in places:
dist = (p.pos - pos).len()
if dist < closest_dist:
closest_dist = dist
closest = p

if closest_dist < 10.0/self.zoom:
self.sel = [closest.name]

This is easy to understand but has the disadvantage of some redundant code
(the distance between ''pos'' and ''some other place'' is calculated both
before and in the loop. So here is an alternative that uses the min()
builtin:

def dp(places, pos):
for i, p in enumerate(places):
yield (p.pos - pos).len(), i, p

if galaxy.places:
pos = somewhere()
dist, _, place = min(dp(galaxy.places.itervalues(), pos))
if dist < 10.0/self.zoom:
self.sel = [place.name]
Extending my existance checking question, how does one check what type
a variable has?




类型(变量)== some_type



isinstance(变量,some_type)


如果变量是子类的实例,也是如此some_type的内容。


但是,如果可能的话,我宁愿避免这种情况,因为你可以很容易地阻止

a函数处理你没有使用的对象想一想你写的时候

和实现相同的方法和属性但是完全不相同的类(google forduck type)。 />

彼得



type(variable) == some_type

or better

isinstance(variable, some_type)

which is also true if variable is an instance of a subclass of some_type.

But again, I''d rather avoid that if possible because you can easily prevent
a function from working with objects you didn''t think of when you wrote it
and that implement the same methods and attributes but are of a totally
unrelated class (google for "duck type").

Peter




" Josiah Manson" < SL ******* @ gmail.com>在消息中写道

news:11 ********************** @ g43g2000cwa.googlegr oups.com ...

"Josiah Manson" <sl*******@gmail.com> wrote in message
news:11**********************@g43g2000cwa.googlegr oups.com...
你好。我是Python的新手,并且无法弄清楚如何检查变量是否存在。在下面的代码中


Python没有变量是其他语言的意义所在。它是
有(无类型)名称绑定到带有值的类型对象。这是一个不同的对象价值模型和一些其他

语言的不同心态。

我已经制作了一个kludge这是有效的,但我认为检查
最近是否存在并且不必首先初始化它会更清楚。
检查完成了怎么办?


你所做的是普通的Python代码。检查''最近''是否必然会发生任何事情可以做但是*是*一个kludge,我会留给你

在其他地方发现。 />
以下代码找到距离最近的位置并拒绝距离太远的地方。

dist = 1e9
nearest = -1


最近=无#是''没有绑定任何东西'的标准'

for n,p in galaxy.places.iteritems():
dif = p.pos - pos
len = dif.len()
如果len< dist和len< 10.0 / self.zoom:
dist = len
nearest = p


如果你生成一系列(距离,地点)对,以

(1e99,无),你可以用min()

内置函数选择最小距离对而不是重写它。

如果最近的话!= -1:


如果最近:#bool(无)== False,bool(anyplace)== True

self.sel = [nearest.name ]

如果你不介意,我还有一些其他的问题需要解决。我是设置dist到1e9,因为这是一个比星系中任何一个地方都要远的地方。是否有更好的方法来初始化dist以使其不可能失败?例如,
会将dist设置为无限工作,这是如何完成的?


也许,取决于编译器。现在,我会坚持使用已知值大于可能的价值。

扩展我的存在检查问题,如何检查什么类型
变量有吗?
Hello. I am very new to Python, and have been unable to figure out how
to check if a variable exists or not. In the following code
Python does not have variables is the sense some other languages do. It
has (typeless) names bound to typed objects with values. This is a
different object-value model and a different mindset from some other
languages.
I have made
a kludge that works, but I think that it would be clearer to check if
closest exists and not have to initialize it in the first place. How is
that check done?
What you did is normal Python code. Checking whether ''closest'' is bound to
anything can be done but that *is* a kludge, which I will leave for you to
discover elsewhere.
The following code finds the closest place to a position and rejects
places that are too far away.

dist = 1e9
closest = -1
closest = None # is the standard for ''not bound to anything''
for n,p in galaxy.places.iteritems():
dif = p.pos - pos
len = dif.len()
if len < dist and len < 10.0/self.zoom:
dist = len
closest = p
If you generate a sequence of (distance, place) pairs, beginning with
(1e99, None), you can select the mimimum distance pair with the min()
builtin function instead of rewriting it.
if closest != -1:
if closest: # bool(None) == False, bool(anyplace) == True
self.sel = [closest.name]

I also have a few other questions to tack on if you don''t mind. I am
setting dist to 1e9, because that is a larger value than any of the
places in the galaxy will be far away. Is there a better way to
initialize dist so that it is impossible for this to fail? For example,
would setting dist to infinity work, and how is that done?
Maybe, depending on the compiler. For now, I would stick with a known
larger-than-possible value.
Extending my existance checking question, how does one check what type
a variable has?




请参阅上面的前两句并查看类型()和isinstance()在

中的第二章库参考。 (如果你没有,请阅读整章

。)

Terry J. Reedy



See the first two sentences above and look up type() and isinstance() in
the 2nd chapter of the Library reference. (And do read that entire chapter
if you have not.)

Terry J. Reedy


这篇关于存在变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆