Felipe
Felipe

Reputation: 71

Inner class in python without affecting the normal operation of the program

I'm learning Python at the same time I'm working on a subject project, and I realized that I have two classes (class senA and senB) that represent two similar elements, therefore, I wondered if those two classes could be grouped in a general class (General class), I was looking at the inner class but unfortunately as I must access the arguments of each class (senA and senB) always generates an error. My code is like this

class senA():
    def __init__(self, arg, arg2):
        self.arg = arg 
        self.arg2 = arg2 

class sensB():
    def __init__(self, arg3):
        self.arg3 = arg3


for i in range (3):
    obj = senA('hx', 'ex')
    objx = sensB ('hello')
    values=list(attrs.values())
    valuesx=list(attrsx.values())
    list_VALORES.append(values)
    list_metodos.append(valuesx)

print(list_metodos)
print(list_VALORES)

and it works well but I would like to associate the classes senA and senB into one called classGeneral

class general():
    class senA():
        def __init__(self, arg, arg2):
            self.arg = arg 
            self.arg2 = arg2 
    
    class sensB():
        def __init__(self, arg3):
            self.arg3 = arg3

but it generates constant errors or for example the program stops recognizing the classes when I instantiate the objects. Any idea how I could solve this

Sorry about my bad English, but I'm not a native English speaker. I try to be as clear as possible

Upvotes: 0

Views: 45

Answers (1)

Evan Gebo
Evan Gebo

Reputation: 51

From what I understand, what you want is to create a separate module to hold the senA and sensB classes. If you create a python file called general.py that holds the class definitions, you can then import that into another python script. So in your main.py, you would add the following line to the top: from general import senA, sensB, and you would be able to use them like normal.

If your classes are all similar and share attributes, than you could also use inheritance. For example:

class General:
    def __init__(self, arg1):
        self.arg1 = arg1  # argument that both senA and sensB use

class senA(General):
    def __init__(self, arg1, arg2):
        super().__init__(arg1)
        self.arg2 = arg2

class sensB(General):
    def __init__(self, arg1, arg2, arg3):
        super().__init__(arg1)
        self.arg2 = arg2
        self.arg3 = arg3

You could then access attributes from those classes as normal, for example:

a = senA('arg1 value', 'arg2 value')
print(a.arg1)  # returns 'arg1 value'
print(a.arg2)  # returns 'arg2 value'

Upvotes: 1

Related Questions