简体   繁体   English

how can I separate member functions from class in python?

[英]how can I separate member functions from class in python?

I'm looking for functionality like this in C:

// driver.h
void some_func(struct _struct* prod);

// driver_thisproduct.c
void some_func(struct _struct* prod) {
// do some stuff
}

// driver_thatproduct.c
void some_func(struct _struct* prod) {
//do some stuff
}

//Makefile(sorry I don't know much about Make)
if model == 'thisproduct'
    obj += driver_thisproduct.o
elif model == 'thatproduct'
    obj += driver_thatproduct.o

by this, I can link different function by linking different object file.

I thought I could do like this in python:


#this_product.py
def some_func(self):
    # do some stuff


# that_product.py
def some_func(self):
    # do some stuff


# driver.py
class Driver:
    def __init__(self):
        product = input()
        if product == 'thisproduct':
             importlib.import_module('thisproduct')
        elif product == 'thatproduct':
             importlib.import_module('thatproduct')

by this, I thought I could do dynamic linking, but I couldn't do it. I've read How can I separate the functions of a class into multiple files?, but I couldn't get what I expected. What did I do wrong? is using importlib.import_module and import ... different?

You could just rename the module selected by user input:您可以重命名用户输入选择的模块:

 #this_product.py def some_func(self): # do some stuff # that_product.py def some_func(self): # do some stuff # driver.py import that_product import this_product userSelectedProduct = None product = input() if product == 'thisproduct': userSelectedProduct = this_product elif product == 'thatproduct': userSelectedProduct = that_product else: # Raise error pass userSelectedProduct.some_func()...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM