python - How can I turn one of the arguments of a function into a string? -


i have code, desired output "the value bar , name b."

class myclass:     def __init__(self, value):         self.value = value  b = myclass("bar")  def foo(var):     true_name = str(var)     print("the value %s , name %s" % (var.value, true_name))  foo(b) 

however, prints the value bar , name <__main__.myclass object @ 0x000000187e979550>, less useful me.

now, i know problems trying true name of variable in python. however, don't need fancy introspection; want convert actual letters typed between parentheses of foo( ) , print that.

to me, sounds simple thing useful in debugging , examining code, can tell object did thing. making fundamental error in assumptions, , terrible idea?

the easiest way passing desired "true name" in along actual reference:

def foo(var):     var, true_name = var     print("the value %s , name %s" % (var.value, true_name))  foo((b, 'b')) 

of course, not guarantee true_name matches passed reference name, it's shorter , clearer way of not guaranteeing possibly-fragile hacks may or may not work.

if want more readable <__main__.myclass object @ 0x000000187e979550>, should define __str__ method in class , print instance. won't need separate foo function anymore. can define __repr__ method precise representation (which string enter interpreter produce equivalent object):

class myclass:     def __init__(self, value):         self.value = value     def __str__(self):         return 'myclass value of {}'.format(self.value)     def __repr__(self):         return "myclass({})".format(repr(self.value)) 

result:

>>> b = myclass("bar") >>> print(b) myclass value of bar >>> b myclass('bar') 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -