Hi,
I am new to python and am wondering is it possible to name a method after a variable. I know I can name a variable after another variable using

test = "temp"
vars()[test] = 123

print temp

this will print 123. so I was thinking something like this for a method:

class myClass:
 def __init__(self, methodName):
  self.vars()[methodName]= "This is the result"

methodName = "myMethod"
o = myClass(methodName)

print o.myMethod

I know it seems long winded but I have a bigger picture in mind.

Thanks in advance for any replies.

Recommended Answers

All 7 Replies

Well sort of ...

class myClass:
    def __init__(self, methodName):
        vars()[methodName] = "This is the result"
        self.__dict__ = vars()

methodName = "myMethod"
q = myClass(methodName)

print( q.myMethod )  # This is the result

You should state what it is you want to do. No offense but there are other solutions and perhaps someone here can come up with a workable solution. Generally you would use (although I can't really understand what you are asking):

class myClass:
    def __init__(self, methodName="This is the result"):
        self.methodName = methodName

MC = myClass()
print MC.methodName

If you want to associate 2 or more items, a dictionary is generally used. But again, if you state the problem, there will probably be better solutions presented.

Hey,
Thanks for the replies. I am trying to create a tree structure for an xml type document. This should work perfect Thanks a lot for the help :-)

Hey,
Thanks for the replies. I am trying to create a tree structure for an xml type document. This should work perfect Thanks a lot for the help :-)

Notice that "This is the result" is a strange value for an item named "methodName" :)

Notice that "This is the result" is a strange value for an item named "methodName" :)

The string "This is the result" is the value of the attribute. The method name would be myMethod in this example.

Ok, thought it was solved but no. This is where I am.

class tree:
 def __init__(self, tag="", attributes={}, value=""):
  self.tag=tag
  self.attributes=attributes
  self.value=value
 def addChild(self, child):
  vars()[child.tag] = child
  self.__dict__=vars()

  

myTree = tree("eventLog")
myChild = tree("event")
print dir(myTree)
myTree.addChild(myChild)

print dir(myTree)

When I do the above it overwrites the methods of the original Class.
Here is the output


I want the output to be


where event will be another tree.

oops, Sorted it.

self.__dict__[child.tag]=vars()
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.