【问题标题】:Using a function to create a instance of a class.使用函数创建类的实例。
【发布时间】:2017-05-16 23:24:42
【问题描述】:

为了满足我正在编写的程序的规范,我需要能够动态生成一个类的实例,该实例可以被代码的其他部分轻松引用。

我环顾四周,找不到答案,我可以在 python 中执行此操作吗?

感谢所有提前回复。

【问题讨论】:

  • 是的,这可以做到。
  • my_instance = MyClass()?
  • 这很模糊。你所说的“在飞行中”是什么意思? “容易引用”是什么意思?
  • 我认为您要求某种类型的动态实例化。元类可能是一种选择。提供一些代码,有人将能够直接为您提供帮助。

标签: python function class object


【解决方案1】:

是的,这是可能的。

例如,您可以创建一个实例并通过函数return它:

def some_function():
    some_instance = int('10')
    return some_instance

a = some_function()   # returns an instance and store it under the name "a"
print(a + 10)  # 20

你也可以使用global(不过我不推荐它):

a = None

def some_other_function():
    # tell the function that you intend to alter the global variable "a",
    # not a local variable "a"
    global a   
    a = int('10')

some_other_function()  # changes the global variable "a"
print(a)   # 10

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    • 1970-01-01
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多