简体   繁体   English

如何使用文件中的文本作为变量名?

[英]How do I use text from a file as a variable name?

How do I use text from a file as a variable name? 如何使用文件中的文本作为变量名? I am pulling values out of an excel file. 我正在从Excel文件中提取值。 I am using xlrd and xlutils with python 3. 我在python 3中使用xlrd和xlutils。

class employee(object):
def __init__(self, name):
    self.name = name
    emp_list.append(name)
def bulk_hours(self,sunday=0,monday=0,tuesday=0,wednesday=0,thursday=0,friday=0,saturday=0):
    self.sunday = sunday
    self.monday = monday
    self.tuesday = tuesday
    self.wednesday = wednesday
    self.thursday = thursday
    self.friday = friday
    self.saturday = saturday

I'm pulling employees out of a spreadsheet. 我正在从电子表格中抽出员工。 I'm trying to use their actual names. 我正在尝试使用他们的真实姓名。 I would love to know any working solution. 我很想知道任何可行的解决方案。 Thanks! 谢谢!

Edit: Pardon my ignorance regarding programming and my horrible post. 编辑:原谅我对编程的无知和我的恐怖帖子。 I'm trying to make a simple program that allows me to load an employees name and work schedule from Excel. 我正在尝试制作一个简单的程序,使我可以从Excel加载员工姓名和工作计划。 I will also make sure any edits are saved back into the spreadsheet. 我还将确保所有编辑都保存回电子表格中。 The employees are labeled by their names. 员工用他们的名字标记。 I'm trying to load their name as a variable so I can do: 我正在尝试将其名称加载为变量,以便可以执行以下操作:

John = employee('John')
John.bulk_hours(0,8,8,8,8,8,0)
Stacy = employee('Stacy')
print(John.monday)

I'm aiming to use their name as the variable I can use dot notation on. 我的目标是使用它们的名称作为可以在其上使用点表示法的变量。 Is this feasible? 这可行吗? Is their some other way I should approach this? 他们是我应该采取其他方式吗?

def load(row):
employee2 = employee(s.cell(row, 0).value)
employee2.bulk_hours(s.cell(row, 1).value, s.cell(row, 2).value, s.cell(row, 3).value, s.cell(row, 4).value,
                     s.cell(row, 5).value, s.cell(row, 6).value, s.cell(row, 7).value)
print(employee2.saturday)

I'm trying to use a function like this to load multiple employees and their hours. 我正在尝试使用这样的功能来加载多个员工及其工作时间。

Could I use a list like this somehow? 我能以某种方式使用这样的列表吗?

worker = ['Joe']
worker[0] = employee('Joe')
worker[0].bulk_hours(0,8,8,8,8,8,0)
print(worker[0].monday)

Thank you for your valuable time. 感谢您的宝贵时间。

Override __getattr__ to transparently access an internal dictionary. 重写__getattr__可以透明地访问内部字典。

class employee(object):
    def __init__(self, ...):
        self._internal_d = extract_data()  # replace extract_data with however you extract CSV values to a dictionary
        ...  # perform other initialization

    def __getattr__(self, name):
        try:
            return self._internal_d[name]
        except KeyError:
            raise AttributeError()

Optionally, you can implement __setattr__ to allow writing properties. (可选)您可以实现__setattr__以允许写入属性。

    def __setattr__(self, name, value):
        return self._internal_d[name] = value

Explanation: when python does variable assignment and can't find a variable name "normally", it checks if an object has __getattr__ . 说明:当python执行变量分配并且“正常”找不到变量名时,它将检查对象是否具有__getattr__ If it does, it calls __getattr__ to get the value with the specified name. 如果是这样,它将调用__getattr__以获取具有指定名称的值。 Thus, you can have dynamic variable names. 因此,您可以具有动态变量名称。 Likewise for __setattr__ . __setattr__

You don't want to use variable names comming from the spreadsheet. 您不想使用电子表格中的变量名。 or one: variable names are internal to the running program, and are not meant to be exported again to an output file. 或一个:变量名是正在运行的程序的内部,并不意味着要再次导出到输出文件。

It is meaningless that the variable is bamed John to represent John's data when the program is running. 在程序运行时,将变量作为John的变量来表示John的数据是没有意义的。 For example, let's suppose it would be possible to create a special markup to use teh variable name - say a ? 例如,假设有可能创建一个特殊的标记来使用变量名-说一个? prefix to fetch the name from another variable. 前缀以从另一个变量获取名称。 Your example would be something like this: 您的示例如下所示:

def row_data(emp_name, *args):
    ?emp_name = employee(emp_name)
    ?emp_name.bulk_hours(*args)
    print(?emp_name.monday)

So, even if at runtime ?emp_name would be exchanged by the contents of the variable name , yur program would still look the same to someone reading the code. 因此,即使在运行时由变量name的内容交换了?emp_name ,您的程序对于阅读代码的人来说还是一样。 So, it makes more sense to simply let the variable be named person or employee or anything, since it can represent any employee (and in fact will, as you loop through the spreadsheet contents, usually the variable will carry the data about one person a time). 因此,简单地将变量命名为personemployee或任何其他名称就更有意义,因为它可以代表任何雇员(实际上,当您遍历电子表格内容时,通常该变量将携带有关一个人的数据)。时间)。

That said, there are times when we do want to have data in the program which do have programmatic labeling. 就是说,有时候我们确实希望在程序中具有程序标记的数据。 but still on those cases - that is what dictionaries are for - create an employees dict, and fill it - and then you can have the names as the keys: 但是在这些情况下-这就是字典的用途-创建employees辞典,并填写它-然后您可以将名称用作键:

employees = dict()
def row_data(emp_name, name):
    person = employee(emp_name)
    person.bulk_hours(*args)
    employes[emp_name] = person

def print_employeers():
    for person_name, person_data in employees.items():
         print(person_name, person_data)

As you can see, it is possible to print all employees data without having to type in their names. 如您所见,可以打印所有员工数据而不必键入他们的姓名。 Also, if it is an interactive program, it is possible to find the data related to a name that is input by the user, using it as the dictionary key. 另外,如果是交互式程序,则可以将其用作字典键来查找与用户输入的名称相关的数据。

However if you intend to have a program to generate other Python source files themselves, and end-up with a .py file for each employee. 但是,如果您打算使用一个程序自己生成其他Python源文件,并最终为每个员工创建一个.py文件。 In that case just make use of a templating engine, like Jinja2, or simply use str's format method. 在那种情况下,只需使用诸如Jinja2之类的模板引擎,或仅使用str的format方法。 (It still hard to imagine why you would need such a thing). (仍然很难想象您为什么会需要这样的东西)。

And, just to have a complete answer, it is possible to create dynamic variable names in Python. 而且,只需要有一个完整的答案,就可以在Python中创建动态的变量名。 However, you will be in the exact same situation I described in the first example here. 但是,您将处于我在这里第一个示例中描述的完全相同的情况。

Global variables for any running code are kept in a regular Python dictionary, which is returned by a call to the globals() function. 任何正在运行的代码的全局变量都保存在常规的Python字典中,该字典通过调用globals()函数返回。 And similarly, values for local variables are kept in a dictionary that returned by a call to locals() - although these do not behave nicely for variables known at compile time (in that case, the local variables are cached in the frame object, and the locals dict is only synchornized with them when it is read, but they can't be written via locals) 同样,局部变量的值保存在由调用locals()返回的字典中-尽管对于编译时已知的变量,它们的表现不佳(在这种情况下,局部变量缓存在frame对象中,并且仅在读取时会与本地人字典同步,但无法通过本地人写)

So: 所以:

def row_data(emp_name, *args):
    globals()[emp_name] = employee(emp_name)
    globals()[emp_name].bulk_hours(*args)
    print(globals()[emp_name].monday)

will work just as you asked - but it is easy to see it is useless. 将按照您的要求工作-但很容易看出它没有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM