from import *

项目结构

假设我们的项目结构如下:

my_project/
|-- dataset/
|   |-- __init__.py
|   |-- imbalance_cifar.py
|   |-- balance_cifar.py
|-- main.py

代码示例

1. dataset/imbalance_cifar.py
# dataset/imbalance_cifar.py

class IMBALANCECIFAR10:
    def __init__(self, mode, cfg):
        self.mode = mode
        self.cfg = cfg
        print(f"Initialized IMBALANCECIFAR10 with mode: {mode} and cfg: {cfg}")

    def get_annotations(self):
        return ["annotation1", "annotation2"]

    def get_num_classes(self):
        return 10
2. dataset/balance_cifar.py
# dataset/balance_cifar.py

class BALANCECIFAR10:
    def __init__(self, mode, cfg):
        self.mode = mode
        self.cfg = cfg
        print(f"Initialized BALANCECIFAR10 with mode: {mode} and cfg: {cfg}")

    def get_annotations(self):
        return ["annotation3", "annotation4"]

    def get_num_classes(self):
        return 10
3. dataset/__init__.py
# dataset/__init__.py

from .imbalance_cifar.py import *
from .balance_cifar.py import *
4. main.py
# main.py

from dataset import *

# 模拟配置文件中的类名字符串
cfg = {
    "DATASET": {
        "DATASET": "IMBALANCECIFAR10"
    }
}

# 动态实例化类
dataset_class = eval(cfg["DATASET"]["DATASET"])
train_set = dataset_class("train", cfg)
valid_set = dataset_class("valid", cfg)

# 调用方法
annotations = train_set.get_annotations()
num_classes = train_set.get_num_classes()

print("Annotations:", annotations)
print("Number of classes:", num_classes)

注意:

如果没有 __init__.py 文件,使用 from ... import ... 的方式导入模块将会失败。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值