我正在用Python开发一种编程语言,您可以在其中编程简单机器的仿真。我编写了一个函数,该函数接受一些输入,对其进行解析,然后找出第一个单词是什么。

现在,对于第一个单词插入,我需要取下一个单词objnamexy


  obj:这是什么类型的简单机器
  name:您要调用的对象
  x:图形上的X坐标
  y:图形上的Y坐标


我已经制作了一个函数nextword,可以遍历代码的其余部分并将每个变量定义为这些单词,因此使用以下代码:

insert pulley JohnThePulley 3 4


它看到第一个单词是insert,并调用了我的insert函数。
然后,将obj设置为pulley,将name设置为JohnThePulley,依此类推。

但是,现在我需要在子类pulley的父类simple_machines下创建一个对象,其名称为JohnThePulley,依此类推。

我遇到的情况是,例如,对于第一个单词插入,我完全不知道下一个单词会是什么,因为他们可以调用子类的所有选择。我需要创建指定的对象以及提供的名称,提供的X坐标和提供的Y坐标。

我尝试使用'{}'.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


我希望在pulley中创建一个名称为JohnThePulley的对象,并且坐标X = 3和Y =4。更简单地说,我想得到的结果是在具有属性nameobj等的名为name.x的类

但是,我得到如下错误:

NameError: name 'obj' is not defined


要么:

SyntaxError: can't assign to function call


第一个显然表示未分配单词name.y,但是第二个显然意味着我无法格式化函数名称或格式化变量名称并将其定义为函数(即使我正在实例化)它作为一个类)。

我究竟做错了什么?我怎样才能解决这个问题?

最佳答案

name 'obj' is not defined是因为obj是在另一个函数中定义的。您必须单独使用MYOBJECT.obj,而不要单独使用obj,并且还必须保留对MYOBJECT的引用。

'{}'.format(obj)(name,x,y)没什么意思,'{}'.format(obj)是字符串,不可调用。

SyntaxError: can't assign to function call是您似乎感兴趣的实际问题。您可以执行globals()['{}'.format(name)] = stuff,但不适用于局部变量和对象(您的linter不会喜欢它)。

如果要对对象执行相同操作,则可以使用setattr(MYOBJECT, '{}'.format(name), '{}'.format(obj))

上面的所有解决方案在技术上都被认为是“丑陋的”,您可能正在寻找的是字典,虽然它不是OOP,但在后台使用字典来精确地处理您想要对对象执行的操作。没有方法的对象本质上是正义字典。

mydico = dict()
mydico[name] = obj


另外,如果name是字符串,则'{}'.format(name)等效于name

10-06 10:38
查看更多