为什么不应该在 python 中动态生成变量名? [英] Why shouldn't one dynamically generate variable names in python?
问题描述
现在我正在学习 Python 并在一些 OOP 概念上苦苦挣扎,其中之一是(对我而言)动态初始化类实例并将它们分配给动态生成的变量名是多么困难,以及我为什么要阅读我一开始就不应该那样做.
在大多数具有类似方向的线程中,答案似乎是这样做是非 Pythonic 的.
有人能详细说明一下吗?
以典型的 OOP 学习案例为例:
LOE = ["graham", "eric", "terry_G", "terry_J", "john", "carol"]类员工():def __init__(self, name, job="喜剧演员"):self.name = 姓名self.job = 工作
为什么这样做更好:
employees = []LOE 中的名称:emp = 员工(姓名)员工.追加(emp)
然后
对于雇员中的emp:如果 emp.name == "eric":打印(emp.job)
代替这个
对于 LOE 中的名称:globals()[name] = Employee(name)
和
print(eric.job)
谢谢!
如果动态生成变量名,不知道存在哪些名称,也无法在代码中使用.
globals()[some_unknown_name] = Foo()
好吧,现在呢?你不能安全地这样做:
eric.bar()
因为你不知道 eric
是否存在.无论如何,您最终都必须使用字典/列表来测试 eric
是否存在:
if 'eric' in globals(): ...
因此,只需将您的对象存储在字典或列表中即可:
people = {}人['eric'] = Foo()
通过这种方式,您还可以安全地迭代一个数据结构来访问所有分组的对象,而无需从其他全局变量中对它们进行排序.
Right now I am learning Python and struggling with a few concepts of OOP, one of that being how difficult it is (to me) to dynamically initialize class instances and assign them to a dynamically generated variable name and why I am reading that I shouldn't do that in the first place.
In most threads with a similar direction, the answer seems to be that it is un-Pythonic to do that.
For example generating variable names on fly in python
Could someone please elaborate?
Take the typical OOP learning case:
LOE = ["graham", "eric", "terry_G", "terry_J", "john", "carol"]
class Employee():
def __init__(self, name, job="comedian"):
self.name = name
self.job = job
Why is it better to do this:
employees = []
for name in LOE:
emp = Employee(name)
employees.append(emp)
and then
for emp in employees:
if emp.name == "eric":
print(emp.job)
instead of this
for name in LOE:
globals()[name] = Employee(name)
and
print(eric.job)
Thanks!
If you dynamically generate variable names, you don't know what names exist, and you can't use them in code.
globals()[some_unknown_name] = Foo()
Well, now what? You can't safely do this:
eric.bar()
Because you don't know whether eric
exists. You'll end up having to test for eric
's existence using dictionaries/lists anyway:
if 'eric' in globals(): ...
So just store your objects in a dictionary or list to begin with:
people = {}
people['eric'] = Foo()
This way you can also safely iterate one data structure to access all your grouped objects without needing to sort them from other global variables.
这篇关于为什么不应该在 python 中动态生成变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!