Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First of all, this:</p> <pre><code>class Swoosh(): spam = '' eggs = '' swallow = '' coconut = '' </code></pre> <p>sets <em>class</em> attributes <code>spam</code>, <code>eggs</code>, etc. Your set_spam method would then presumably go ahead and create <em>object</em> attributes of the same name that hide the class attributes. In other words, defining these attributes have no effect and just confuses things.</p> <p>I would do it like this, if all the variables are optional:</p> <pre><code>class Swoosh(): def __init__(self, spam="", eggs="", swallow="", coconut=""): self.spam = spam self.eggs = eggs self.swallow = swallow self.coconut = coconut </code></pre> <p>Then you can create objects like this:</p> <pre><code>o1 = Swoosh(eggs="Eggs!", coconut="Carried by the husk") </code></pre> <p>If, say, spam and eggs are mandatory, then substitute with</p> <pre><code> def __init__(self, spam, eggs, swallow="", coconut=""): </code></pre> <p>And don't use setters and getters at all. If you need to later on, you can seamlessly replace a regular attribute with a property by adding code like this to your class:</p> <pre><code> def get_spam(self): return self._spam def set_spam(self, value): self._spam = " ".join([str(value)] * 5) spam = property(get_spam, set_spam) </code></pre> <p>With the above change, this:</p> <pre><code>o2 = Swoosh(eggs="yes", spam="spam") print o2.spam </code></pre> <p>prints</p> <pre><code>spam spam spam spam spam </code></pre> <p><strong>Note:</strong> As Dave Webb points out in his answer, you need to subclass <code>object</code> for properties to work, unless you use python 3.0+, in which case classes implicitly subclass <code>object</code>. Oh, and <em>do</em> follow Sean Vieira's link to the <em>Python is not Java</em> article. It's a must-read.</p>
    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.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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