Kendi rulo istemiyorsanız, tam olarak bunu yapar pydoc
modülünde mevcut bir fonksiyonu vardır:
from pydoc import locate
my_class = locate('my_package.my_module.MyClass')
burada listelenen diğerlerine göre bu yaklaşımın avantajı locate
sağlanan noktalı yolda herhangi piton nesne değil, j bulacaksınız olmasıdır doğrudan bir modül içinde bir nesne. Örneğin. my_package.my_module.MyClass.attr
.
def locate(path, forceload=0):
"""Locate an object by name or dotted path, importing as necessary."""
parts = [part for part in split(path, '.') if part]
module, n = None, 0
while n < len(parts):
nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
if nextmodule: module, n = nextmodule, n + 1
else: break
if module:
object = module
else:
object = __builtin__
for part in parts[n:]:
try:
object = getattr(object, part)
except AttributeError:
return None
return object
O pydoc.safeimport
fonksiyonu dayanır: Onların tarifi ne meraklı iseniz
, burada fonksiyon.
"""Import a module; handle errors; return None if the module isn't found.
If the module *is* found but an exception occurs, it's wrapped in an
ErrorDuringImport exception and reraised. Unlike __import__, if a
package path is specified, the module at the end of the path is returned,
not the package at the beginning. If the optional 'forceload' argument
is 1, we reload the module from disk (unless it's a dynamic extension)."""
Bir değişkene de sınıf referansı. – pjesi
Bu, aşağıdakilerin bir kopyası gibi görünüyor: http://stackoverflow.com/questions/452969/does-python-have-an-equivalent-to-java-class-forname – cdleary
Doğru bir kopyadır, bulmak için teşekkürler – pjesi