Search code examples
python-3.xinstance-variables

Can you create an instance from a method within a class?


I am writing a program that creates combinations of the characters in strings. I have a class that does this named StringRecomb, which takes in two inputs as strings in a list i.e. ["AA", "BB"]. The recombinations method returns characters left and right reversed from the strings in the list and returns them in a set i.e. {AB, BA}.

class StringRecomb:

    def __init__(self,strings):
        self.strings= strings


    def recombinations(self):
        //some code to create recombinations left and right char of each string in list
        return recombinations_set


    def method1(self):
        //code currently to access the recombinations list:
        recombinations_set = self.recombinations()
        //do something with recombinations list to get method1_out
        return method1_out

What I'm asking is can the reactions returned in the reaction method be an instance? To then be used and manipulated in other methods within the class. For example, recombinations2 takes the self.recombinations from the first recombinations method and changes it. Something like... (* where I have changed code)

class StringRecomb:

    def __init__(self,strings):
        self.strings= strings

    def recombinations(self):
        //some code to create recombinations left and right char of each string in list
        return self.recombinations_set *

    def method1(self, self.recombinations_set): *
        //use self.recombinations_set from the parameter of the method to access the set
        return method1_out

    def recombinations2(self, self.recombinations_set): *
        //Method to change the self.recombinations to right to left i.e. {BA, AB} *
        return self.recombinations *

I hope I have explained this well enough.


Solution

  • I don't know exactly what you mean, but you can store the recombinations in your class just like this:

    class StringRecomb:
        def __init__(self, strings):
            self.strings = strings
            self.recombinations = None
    
        def recombinations(self):
            # some code to create recombinations left and right char of each string in list
            recombinations_set = foo()
            self.recombinations = recombinations_set
    
        def method1(self):
            # code currently to access the recombinations list
            self.recombinations = foo2()
    
        def recombinations2(self):
            # Method to change the self.recombinations to right to left i.e. {BA, AB} *
            self.recombinations = foo3()