If I have a class variable being passed to a function, is there a way that I can get the class that the variable is from?

class someclass:
	def __init__(self):
		self.somevariable='somevalue'

	def somefunction(self):
		print('gotta get here')

def someotherfunction(somevariable):
	somevariable.needparentclasshere.somefunction()

myclass=someclass()
someotherfunction(myclass.somevariable)#this needs to print 'gotta get here'

Recommended Answers

All 2 Replies

Only this works:

class someclass:
	def __init__(self):
		self.somevariable='somevalue'

	def somefunction(self):
		print('gotta get here')

def someotherfunction(instance):
	instance.somefunction()

myclass=someclass()
someotherfunction(myclass)#this needs to print 'gotta get here'

as myclass.somevariable is only one string and has nothing connection with someclass. Or must save self in init:

class someclass:
	def __init__(self):
		self.somevariable= self, 'somevalue'

	def somefunction(self):
		print('gotta get here')

def someotherfunction((instance, value)):
	instance.somefunction()

myclass=someclass()
someotherfunction(myclass.somevariable)#this needs to print 'gotta get here'

You perhaps want something along the lines of:

class someclass:
    def __init__(self):
        self.somevariable='somevalue'
     
    def somefunction(self):
        print('gotta get here')
     
def someotherfunction(class_instance):
    print "somevariable -->", class_instance.somevariable

    print "somefunction -->", 
    class_instance.somefunction()
     
myclass=someclass()
someotherfunction(myclass)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.