0

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.

4
Contributors
7
Replies
8
Views
5 Years
Discussion Span
Last Post by bertm81
0

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
0

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.

Edited by woooee: n/a

0

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 :-)

0

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" :)

0

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.

0

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.

This question has already been answered. Start a new discussion instead.
Be sure to adhere to our posting rules.