如何从导入的模型中获取所有类的实例?

时间:2016-10-27 12:56:14

标签: python class python-3.x oop

Person是一个新类,它有两个属性:heightweight

class People:

    def __init__(self, height, weight):
        self.height = height
        self.weight = weight

我想要导入另一个file.py,它具有相同的类和此类的一些对象。例如:

p1 = People(185, 87)
p2 = People(167, 73)
p3 = People(173, 90)

但我不知道每个变量如何调用以及给定文件中存在多少变量。 如何获取导入文件的所有对象?目标是从多个文件创建对象的list()。

1 个答案:

答案 0 :(得分:1)

执行此操作的好方法是使用pred参数inspect.getmembers

首先,您可以使用inspect.isclass在模块中获取所有用户定义的类,然后创建一个新的谓词来捕获您之前获得的类的任何实例。

最初,使用isclass中定义的inspect轻松抓取课程:

from inspect import getmembers, isclass
# the module defining the objects
import obj

# getmembers returns list of (name, val) tuples, grab vals
clses = tuple(x[1] for x in getmembers(obj, isclass))

现在,clses是一个类的元组:

print(clses) # (obj.People,)

如果事先已知类, 上一步当然是不需要的;只需创建一个您需要查找的类的元组,然后继续下一步。

然后,您可以创建一个新的谓词(一个简单的lambda就足够了),它可以抓取clses中任何类的实例的对象:

pred = lambda x: isinstance(x, clses)
instances = getmembers(obj, pred)

现在的结果是instances填充了obj True isinstance pred签入print(instances) [('p1', <obj.People at 0x7f436739ce10>), ('p2', <obj.People at 0x7f436739c898>), ('p3', <obj.People at 0x7f436739cc18>)] 模块中的任何名称:< / p>

-----> IBM SDK for Node.js Buildpack v3.8-20161006-1211
   Based on Cloud Foundry Node.js Buildpack v1.5.20
-----> Creating runtime environment
   NPM_CONFIG_LOGLEVEL=error
   NPM_CONFIG_PRODUCTION=true
   NODE_ENV=production
   NODE_MODULES_CACHE=false
-----> Installing binaries
   engines.node (package.json):  >=6.7.0
   engines.npm (package.json):   >=3.10.3
   Resolving node version >=6.7.0 via 'node-version-resolver'
   Installing IBM SDK for Node.js (6.7.0) from cache
   Resolving npm version >=3.10.3 via semver.io...
   Downloading and installing npm 3.10.9 (replacing version 3.10.3)...
-----> Restoring cache
   Skipping cache restore (disabled by config)
-----> Checking and configuring service extensions before installing dependencies
-----> Building dependencies
   Installing node modules (package.json)
   npm ERR! Linux 3.19.0-33-generic
   npm ERR! argv "/tmp/staged/app/vendor/node/bin/node" "/tmp/staged/app/vendor/node/bin/npm" "install" "--unsafe-perm" "--userconfig" "/tmp/staged/app/.npmrc"
   npm ERR! node v6.7.0
   npm ERR! npm  v3.10.9
   npm ERR! code EREADFILE
   npm ERR! Error extracting /home/vcap/.npm/fs/0.0.0/package.tgz archive: ENOENT: no such file or directory, open '/home/vcap/.npm/fs/0.0.0/package.tgz'
   npm ERR!
   npm ERR!     <https://github.com/npm/npm/issues>
   npm ERR! If you need help, you may report this error at:
   npm ERR! Please include the following file with any support request:
   npm ERR!     /tmp/staged/app/npm-debug.log
-----> Build failed