我有以下模块结构:
Person.py
内的代码是:
class person:
def __init__(self,name,age):
self.name = name
self.age = age
def displayage(self):
print ("Your age is {0}".format(self.age))
内部Vechile.py
是:
class vechile:
def __init__(self,type):
self.type = type
def display_type(self):
print ("Your vechile type is {}".format(self.type))
内部__init__.py
:
pass
在Test.py
内,我想知道Person.py
和Vechile.py
中定义的类名。
import inspect
from Fetch import Vechile
from Fetch import Person
modules = ['Vechile','Person']
for module in modules:
for name, obj in inspect.getmembers(module):
if inspect.isclass(name):
print (obj)
v = Vechile.vechile("Auto")
print (v)
我得到的答案只有这个:
<Fetch.Vechile.vechile object at 0x0000000000DD0C18>
我哪里错了?如何获取Person
和Vechile
中定义的类列表?
答案 0 :(得分:3)
您当前正在将模块名称作为字符串传递给inspect.getmembers
:
modules = ['Vechile','Person']
for module in modules:
for name, obj in inspect.getmembers(module):
...
这将查看字符串实例的成员,而不是模块的成员。要查找模块的成员,为其提供模块。
modules = [Vechile, Person]
for module in modules:
for name, obj in inspect.getmembers(module, inspect.isclass):
# no need to check if is class here
...
答案 1 :(得分:0)
我想我修正了你的错误。
Person.py
class person():
def __init__(self,name,age):
self.name = name
self.age = age
def displayage(self):
return("Your age is {0}".format(self.age))
Vechile.py
class vechile():
def __init__(self,type):
self.type = type
def display_type(self):
return("Your vechile type is {}".format(self.type))
Test.py(保持不变)
import inspect
from Fetch import Vechile
from Fetch import Person
modules = ['Vechile','Person']
for module in modules:
for name, obj in inspect.getmembers(module):
if inspect.isclass(name):
print (obj)
v = Vechile.vechile.display_type("Auto")
print (v)
答案 2 :(得分:0)
main.py
中有两个错误。这是一个固定版本,其中包含更改:
import inspect
from Fetch import Vechile
from Fetch import Person
modules = [Vechile, Person] # changed
for module in modules:
for name, obj in inspect.getmembers(module):
if inspect.isclass(obj): # changed
print(obj)
v = Vechile.vechile("Auto")
print(v)