【问题标题】:Using a function define var and then passing to a constructor使用函数定义 var 然后传递给构造函数
【发布时间】:2019-09-17 22:28:55
【问题描述】:

我希望客户端代码调用一个函数,该函数将用户输入的值分配给变量并将它们传递给一个对象以用作用户定义的属性。

但我无法为对象调用任何方法

我尝试在函数中包含对象的方法,但它似乎没有改变任何东西,同样的错误。

def function():

    a = input("blahblah")
    the_object = foo(a)

class foo(object):
    def __init__(a):
        self.a = a   #This works fine
        print(self.a) 

    def DoThing():   #This does not
        print(self.a)

#Main
function()
the_object.DoThing()

我可以看到函数被调用,对象被创建。 但是当我尝试调用任何方法时,我不断收到错误

NameError:名称“the_object”未定义

【问题讨论】:

标签: python function oop object nameerror


【解决方案1】:
def function():
    a = input("blahblah")
    return foo(a)

class foo(object):
    def __init__(object):
        self.a = object
        print(self.a) 

    def DoThing():
        print(self.a)

#Main
the_object = function()
the_object.DoThing()

class foo(object):
    def __init__(object):
        self.a = object
        print(self.a) 

    def DoThing():
        print(self.a)

the_object = foo("blahblah")
the_object.DoThing()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 2011-09-05
    • 1970-01-01
    相关资源
    最近更新 更多