给定一个字符串作为Python函数的用户输入,如果在当前定义的命名空间中有一个具有该名称的类,我想从中获取一个类对象.从本质上讲,我想要一个能产生这种结果的函数的实现:
class Foo:
pass
str_to_class("Foo")
==> <class __main__.Foo at 0x69ba0>
Run Code Online (Sandbox Code Playgroud)
这是可能吗?
给定一个Python类的字符串,例如my_package.my_module.MyClass,加载它的最佳方法是什么?
换句话说,我正在寻找Class.forName()Java中的等效函数,Python中的函数.它需要在Google App Engine上运行.
最好这是一个函数,它接受类的FQN作为字符串,并返回对类的引用:
my_class = load_class('my_package.my_module.MyClass')
my_instance = my_class()
Run Code Online (Sandbox Code Playgroud) 我试图importlib.import_module在Python 2.7.2中使用并遇到奇怪的错误.
考虑以下目录结构:
a
|
+ - __init__.py
- b
|
+ - __init__.py
- c.py
a/b/__init__.py 具有以下代码:
import importlib
mod = importlib.import_module("c")
(在实际代码中"c"有一个名字.)
试着import a.b,产生以下错误:
>>> import a.b
Traceback (most recent call last):
File "", line 1, in
File "a/b/__init__.py", line 3, in
mod = importlib.import_module("c")
File "/opt/Python-2.7.2/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
ImportError: No module named c
我错过了什么?
谢谢!
我有类名列表,想要动态创建它们的实例.例如:
names=[
'foo.baa.a',
'foo.daa.c',
'foo.AA',
....
]
def save(cName, argument):
aa = create_instance(cName) # how to do it?
aa.save(argument)
save(random_from(names), arg)
Run Code Online (Sandbox Code Playgroud)
如何在Python中动态创建该实例?谢谢!
我正在使用构建器模式来分离一堆不同的配置可能性.基本上,我有一堆名为ID的类(类似于ID12345).这些都继承自基础构建器类.在我的脚本中,每次运行此应用程序时,我都需要为每个类(大约50个)实例化一个实例.所以,我试图看看是否代替做这样的事情:
ProcessDirector = ProcessDirector()
ID12345 = ID12345()
ID01234 = ID01234()
ProcessDirector.construct(ID12345)
ProcessDirector.construct(ID01234)
ID12345.run()
ID01234.run()
Run Code Online (Sandbox Code Playgroud)
我可以做这样的事情(我知道这不起作用):
IDS = ["ID12345", "ID01234"]
ProcessDirector = ProcessDirector()
for id in IDS:
builder = id() #some how instantiate class from string
ProcessDirector.construct(builder)
builder.run()
Run Code Online (Sandbox Code Playgroud)
这样,当我需要在将来添加一个新的时,我所要做的就是将ID添加到IDS列表中,而不是在整个代码中添加新的ID.
看起来根据数据的来源,有一些不同的意见.这些ID输入到其他人无法访问的文件中.我不是从命令行读取字符串,并且我希望将来在添加新ID时能够进行少量更改.
由于python中的所有内容都是一个对象,我想知道是否有一种方法可以使用类的名称初始化一个类对象
例如,
class Foo:
"""Class Foo"""
Run Code Online (Sandbox Code Playgroud)
我怎么能通过"Foo"访问这个类,就像这样 c = get_class("Foo")
从url名称获取通用视图类的推荐方法是什么?
url(r'^$', HomeView.as_view(), name='home')
Run Code Online (Sandbox Code Playgroud)
因此,对于'home',我想获得HomeView类.
我有一个基类,它有一个方法,创建一个子类的实例,调用与输入字符串相同.
之前通过将子类和基类放在同一个文件中,并执行类似的操作globals()[name].
但是,现在,我已将子类拆分为其他文件.它们每个都import base在顶部有一个语句,所以我不能简单地在我的基类中导入子类,或者只有一个循环导入链.
这有什么解决方法吗?
在base.py中:
from basefactory import BaseFactory
class Base:
def __init__(self, arg1, arg2):
...
def resolve(self, element):
className = typing.getClassName(element)
return BaseFactory.getInstance(className, element, self)
Run Code Online (Sandbox Code Playgroud)
在basefactory.py中:
from file1 import *
from file2 import *
...
class BaseFactory:
@staticmethod
def getInstance(name, arg1, arg2):
subclass = globals()[name]
return subclass(arg1, arg2)
Run Code Online (Sandbox Code Playgroud)
在file1.py中:
from base import Base
class subclass1(Base):
def foo(self):
return self.arg1
Run Code Online (Sandbox Code Playgroud) 我有一些代码希望以比我的直觉想要的更优雅的方式实现。我将尽力描述我正在尝试的事情。
\n\nclass Fruit():\n pass\n\nclass Apple(Fruit):\n pass\n\nclass Orange(Fruit):\n pass\n\ndef create_fruit(fruit_type):\n test = ???? # code here to create instance of fruit of desired type called test\nRun Code Online (Sandbox Code Playgroud)\n\n好的,希望这段代码能有意义。我在模块中有一个函数,它需要一堆参数来创建类的实例。理想情况下,我希望传递一个参数来说明要创建的类的类型(但它们都是同一超类的实例或子类)。每个子类的参数将是相同的(截至目前)。
\n\n我可能可以很容易地用 if 语句做一些事情并组合在一起(例如,,,,if fruit_type==1i test=Apple(),,f fruit_type == 2等test=Orange()\xe2\x80\xa6),但是在尝试提高作为一名Python程序员时,我想知道是否有更好的这样做的方法。我已经简要阅读了装饰器和函数式编程(尽管它对我来说仍然相当抽象,并且需要更多时间来理解),所以也许这也是同样的脉络?
我有一个类,试图根据传递给它的变量名实例化另一个类.它抱怨'str'对象不可调用.这样做的正确方法是什么?
def MyClass:
def __init__(self, otherName):
self.other = otherName()
Run Code Online (Sandbox Code Playgroud)
编辑:这是我的全部代码,有什么我应该做的不同?Python中的eval是邪恶的吗?
#!/usr/bin/python
class Model:
def get_post(self, id):
# Would query database, perhaps
return {"title": "Python :: Test Page", "body": "Test page using Python!"}
class Controller:
def __init__(self, viewName):
self.model = Model()
self.view = viewName()
def main(self):
post = self.model.get_post(1)
self.view.display(post)
class View:
def header(self, item):
print "Content-type: text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>%(title)s</title>" % item
print "</head>"
print "<body>"
def footer(self, item):
print "</body>"
print "</html>"
class Blog(View):
def display(self,item): …Run Code Online (Sandbox Code Playgroud) 我试图在python中找到关于反射的一些信息.我发现了一篇维基百科文章,它将此作为代码片段:
# without reflection
Foo().hello()
# with reflection
getattr(globals()['Foo'](), 'hello')()
Run Code Online (Sandbox Code Playgroud)
我无法让这个工作.我真正需要的是一种实例化对象的方法.所以,如果我有一个字符串'Foo',我希望能够得到一个Foo类型的对象.就像在java中我可以这样说:Class.forName("Foo")
刚刚发现这个......想知道为什么我以前找不到这个: python是否具有Java Class.forName()的等价物?
我的要求是使用变量值来引用Python中的类/字典.作为示例,我有以下数据: -
class test1:
pass
class test2:
pass
test1_dict = {}
test2_dict = {}
testvariable = "test1"
Run Code Online (Sandbox Code Playgroud)
现在我想检查值testvariable并创建一个类的实例并将其附加到字典中.
例如
if testvariable == "test1":
test1inst = test1()
test1_dict["test1"] = test1inst
elif testvariable == "test2":
test2inst = test2()
test2_dict["test2"] = test2inst
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我必须明确地使用if/else来检查值testvariable并相应地执行操作.
在我的真实场景中,我可以有多个值,testvariable并且可能有多个if/else需要检查的地方.那么,有可能以某种方式,我可以使用testvariable直接的值来引用字典/类实例而不使用if/else.
python ×11
reflection ×3
django ×2
import ×2
base ×1
class ×1
inheritance ×1
module ×1
new-operator ×1
object ×1
python-3.8 ×1
python-3.x ×1
subclass ×1