Note that there are some explanatory texts on larger screens.

plurals
  1. POAccessing the name of an instance in Python for printing
    primarykey
    data
    text
    <p>So as part of problem 17.6 in "Think Like a Computer Scientist", I've written a class called Kangaroo:</p> <pre><code>class Kangaroo(object): def __init__(self, pouch_contents = []): self.pouch_contents = pouch_contents def __str__(self): ''' &gt;&gt;&gt; kanga = Kangaroo() &gt;&gt;&gt; kanga.put_in_pouch('olfactory') &gt;&gt;&gt; kanga.put_in_pouch(7) &gt;&gt;&gt; kanga.put_in_pouch(8) &gt;&gt;&gt; kanga.put_in_pouch(9) &gt;&gt;&gt; print kanga "In kanga's pouch there is: ['olfactory', 7, 8, 9]" ''' return "In %s's pouch there is: %s" % (object.__str__(self), self.pouch_contents) def put_in_pouch(self, other): ''' &gt;&gt;&gt; kanga = Kangaroo() &gt;&gt;&gt; kanga.put_in_pouch('olfactory') &gt;&gt;&gt; kanga.put_in_pouch(7) &gt;&gt;&gt; kanga.put_in_pouch(8) &gt;&gt;&gt; kanga.put_in_pouch(9) &gt;&gt;&gt; kanga.pouch_contents ['olfactory', 7, 8, 9] ''' self.pouch_contents.append(other) </code></pre> <p>What's driving me nuts is that I'd like to be able to write a string method that would pass the unit test underneath <code>__str__</code> as written. What I'm getting now instead is:</p> <pre><code>In &lt;__main__.Kangaroo object at 0x4dd870&gt;'s pouch there is: ['olfactory', 7, 8, 9] </code></pre> <p>Bascially, what I'm wondering if there is some function that I can perform on kanga = Kangaroo such that the output of the function is those 5 characters, i.e. function(kanga) -> "kanga".</p> <p>Any ideas? </p> <p><strong>Edit:</strong> Reading the first answer has made me realize that there is a more concise way to ask my original question. Is there a way to rewrite <code>__init__</code> such that the following code is valid as written?</p> <pre><code>&gt;&gt;&gt; somename = Kangaroo() &gt;&gt;&gt; somename.name 'somename' </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload