gpt4 book ai didi

python - 使用检查返回包内定义的类列表

转载 作者:行者123 更新时间:2023-11-30 22:35:11 26 4
gpt4 key购买 nike

我有以下模块结构:

Directory structure of my code

里面的代码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

最佳答案

您当前正在将模块名称作为字符串传递到此处的 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
...

关于python - 使用检查返回包内定义的类列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44650052/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com