-1

I have accepted the answer to this question by @dtanabe Here is my code

def abc(): pass
x = abc
class label:
    def __init__(self,fnname):
        self.lbl = fnname
    def __repr__(self):
        repr(self.lbl)
    def __str__(self):
        # how should this be defined?
        # I have no objection if other class functions
        # or variables need to be defined

u = label(x)

I would like print(u) to respond with abc (three characters) on the screen and print([u]) to respond with [abc] (five characters). In each of these two cases, I do not want to see on screen any single or double quote mark anywhere near the strings of length 3 or 5.

Of course, I would like the analogous behaviour for a function abcdefg, with print(u) giving rise to abcdefg on the screen and print([u]) giving rise to [abcdefg] on the screen.

Your answer is allowed to change the definition of the class, but it is not allowed to change anything outside the class definition.

David Epstein
  • 433
  • 4
  • 14

1 Answers1

1

Don't use repr() in your __repr__ implementation, because that is what adds the quote marks:

def myFunction(): pass

some_ref_to_a_func = myFunction

class Label:
    def __init__(self, value):
        self.value = value
    def __repr__(self):
        return self.value.__name__
    def __str__(self):
        return self.value.__name__

x = Label(some_ref_to_a_func)
print(x)  # prints: some_ref_to_a_func
dtanabe
  • 1,611
  • 9
  • 18
  • Ah made the assumption that your values were strings; adapted the code accordingly. – dtanabe Jan 11 '19 at 22:15
  • But you have omitted the first two lines of the code in my question. If you replace them, and use my x = label(u) instead of your x, then your version generates a TypeError. I will edit my question to clarify. – David Epstein Jan 11 '19 at 22:26
  • Agree with @juanpa.arrivillaga about the name being confusing—I originally read your `label` class as taking the name of the function (a string) instead of the function itself. – dtanabe Jan 11 '19 at 22:31
  • I edited the question to make the rules of the game clearer. You are allowed to change the definition of the class in any way you like. You are not allowed to change anything at all in code that is not part of the class definition. – David Epstein Jan 11 '19 at 23:07
  • @juanpa.arrivillaga Can you please remove your statement that my question is a duplicate. – David Epstein Jan 12 '19 at 06:01
  • A very nice and simple answer. I didn't believe it, until I tried it, as your code did not include the line print([x]). I will try to incorporate my idea into my code, where there are further complications, but it looks good. I was thinking of something much more complex. Now that I have seen that it works, I understand your point about using an appropriate definition of repr. – David Epstein Jan 12 '19 at 10:25
  • I meant 'your idea' rather than 'my idea' but the system wouldn't let me edit. – David Epstein Jan 12 '19 at 10:37