简体   繁体   English

Python 中的动态对象命名和类调用

[英]Dynamic Object Naming and Class Calling in Python

I'm developing a programming language in Python where you can program a simulation of simple machines.我正在用 Python 开发一种编程语言,您可以在其中对简单机器的模拟进行编程。 I have written a function that takes some input, parses it, and finds out what the first word is.我写了一个函数,它接受一些输入,解析它,并找出第一个单词是什么。

Now, for the first word insert, I need to take the next words obj , name , x , and y .现在,对于第一个单词 insert,我需要取下一个单词objnamexy

obj : what type of simple machine it is obj : 它是什么类型的简单机器
name : what you want to call the object name :您要调用的对象
x : X coordinate on the graph x : 图形上的 X 坐标
y : Y coordinate on the graph y : 图形上的 Y 坐标

I have already made a function nextword that iterates through the rest of the code and defines each variable as those words, so with the following code:我已经创建了一个函数nextword ,它遍历代码的其余部分并将每个变量定义为这些单词,因此使用以下代码:

insert pulley JohnThePulley 3 4

It sees first word is insert , and calls my insert function.它看到第一个词是insert ,并调用我的insert函数。
Then, it sets obj to pulley , name to JohnThePulley , and so on.然后,它将obj设置为pulley ,将nameJohnThePulley ,依此类推。

However, now I need to make an object in the daughter class pulley , under the mother class simple_machines , that has the name JohnThePulley , etc.但是,现在我需要在子类pulley创建一个对象,在母类simple_machines ,名称为JohnThePulley等。

The situation I'm in is that for the first word insert, for example, I don't know at all what the next word will be, from all the choices of daughter classes that they can call.我所处的情况是,例如,对于第一个单词 insert,从他们可以调用的所有子类选择中,我完全不知道下一个单词是什么。 I need to create the specified object along with the provided name, the provided X coordinate and the provided Y coordinate.我需要创建指定的对象以及提供的名称、提供的 X 坐标和提供的 Y 坐标。

I have tried doing simple formatting in python using '{}'.format(name) or .format(obj) , but those don't work.我曾尝试使用'{}'.format(name).format(obj)在 python 中进行简单的格式化,但这些都不起作用。

# Insert function
def insert(code):
    c = 4
    syntax = np.array([obj, name, x, y])
    nextword(parser.code_array, syntax, c)
    objc += 1
    return


# Nextword function, code_array[0] is insert, syntax is an array that
# contains all the variables that need to be defined for any function
def nextword(code_array, syntax, c):
    assert len(code_array) == c + 1, "Too Many Words!"
    for m in range(0, c):
        syntax[m] = code_array[m + 1]
    return


# Mother Class simple_machines with properties
class simple_machines:
    def __init__(self, obj, name, x, y, coords):
        self.obj = (
            obj
        )  # what type of obj, in this case, pulley
        self.name = name  # name, JohnThePulley
        self.x = x  # 3 in this case
        self.y = y  # 4 in this case
        self.coords = (x, y)  # (3,4) in this case
        return


# Pulley Class, here so I can later define special properties for a pulley
class pulley(simple_machines):
    def __init__(self, name, x, y):
        super(simple_machines, self).__init__()
        return


# Code that I tried
def insert(code):
    c = 4
    syntax = np.array([obj, name, x, y])
    nextword(parser.code_array, syntax, c)
    "{}".format(name) = "{}".format(obj)(
        name, x, y
    )  # this is what my
    # instantiation would look like, formatting an object with name, then
    # calling a class formatted with obj, and inserting their input of
    # name,x,y as the properties
    return

I expect an object in pulley to be created with the name JohnThePulley , and the coordinates X = 3 and Y = 4. What I'd like to result in, in simpler terms, is an object called name in a class called obj with the attributes name.x , name.y , etc我希望在pulley中创建一个名为JohnThePulley ,坐标为 X = 3 和 Y = 4。简单来说,我想要产生的是一个名为obj的类中名为name的对象属性name.x , name.y

However, I get errors like:但是,我收到如下错误:

NameError: name 'obj' is not defined

or:或者:

SyntaxError: can't assign to function call

The first one apparently means that the word obj isn't being assigned, but the second one apparently means that I can't format a function name or format a variable name and define it as a function (even though I'm instantiating it as a class).第一个显然意味着没有分配obj这个词,但第二个显然意味着我不能格式化函数名或格式化变量名并将其定义为函数(即使我将它实例化为一类)。

What am I doing wrong?我究竟做错了什么? How can I fix this?我怎样才能解决这个问题?

name 'obj' is not defined is because obj is defined in another function. name 'obj' is not defined是因为obj是在另一个函数中定义的。 You have to use MYOBJECT.obj , not obj alone, and also keep a reference to MYOBJECT .您必须使用MYOBJECT.obj ,而不仅仅是obj ,并且还要保留对MYOBJECT的引用。

'{}'.format(obj)(name,x,y) doesn't mean anything, '{}'.format(obj) is a string and isn't callable. '{}'.format(obj)(name,x,y)没有任何意义, '{}'.format(obj)是一个字符串,不可调用。

SyntaxError: can't assign to function call is the actual problem you seem to be interested in. You could do globals()['{}'.format(name)] = stuff but it doesn't work for local variables and objects (and your linter is not going to like it). SyntaxError: can't assign to function call是您似乎感兴趣的实际问题。您可以执行globals()['{}'.format(name)] = stuff但它不适用于局部变量和对象(你的短绒不会喜欢它)。

If you want to do the same for objects you can use setattr(MYOBJECT, '{}'.format(name), '{}'.format(obj))如果你想对对象做同样的事情,你可以使用setattr(MYOBJECT, '{}'.format(name), '{}'.format(obj))

All of the solutions above are in technical terms considered "ugly" and what you're probably looking for is a dictionary, while it isn't OOP, dictionaries are used behind the scenes to handle exactly what you want to do with objects.上面的所有解决方案在技术术语中都被认为是“丑陋的”,您可能正在寻找的是字典,虽然它不是面向对象编程,但在幕后使用字典来准确处理您想要对对象执行的操作。 An object without methods is essentially a just dictionary.没有方法的对象本质上就是一个字典。

mydico = dict()
mydico[name] = obj

Also, if name is a string, then '{}'.format(name) is equivalent to name .此外,如果name是字符串,则'{}'.format(name)等效于name

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

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