Note that there are some explanatory texts on larger screens.

plurals
  1. POGiving 'NoneType' object attributes
    primarykey
    data
    text
    <p>Is it possible to assign attributes to the <code>'Nonetype' object</code> to tell Python what to do if they are called?</p> <p>Here is my problem: </p> <p>I have a class that functions as a library to store instances of <code>myOtherObject</code>. Before adding an instance, it first checks if that key already exists and then appends the data to the instance assigned to that key rather than overwriting it. </p> <pre><code>class MyClass: def __init__(self): self.myLibrary = {} def __setitem__(self, key, item): if key not in self.myLibrary: self.myLibrary[key] = myOtherObject(name=item[0], attr1=[item[1]], attr2=[item[2]]) else: self.myLibrary[key].attr1.append(item[1]) self.myLibrary[key].attr2.append(item[2]) def __getitem__(self, key): if key in self.myLibrary: return self.myLibrary[key] else: return None #??? </code></pre> <p>When retrieving data from the library it should check if the key exists too, and only return the assigned object if the key exists. This works fine or calling just the object, however not when calling the attributes of that object:</p> <pre><code>&gt;&gt;&gt; o = MyClass() &gt;&gt;&gt; o['key1'] = ['name1','b','c'] &gt;&gt;&gt; o['key1'] &lt;__main__.myOtherObject instance at 0x05509B48&gt; &gt;&gt;&gt; o['key1'].attr1 'b' &gt;&gt;&gt; o['key2'] &gt;&gt;&gt; o['key2'].attr1 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'NoneType' object has no attribute 'attr1' </code></pre> <p>Can I somehow tell Python not to do anything and just return <code>None</code> when attributes <code>attr1</code> and <code>attr2</code> are called from the <code>'NoneType' object</code>?</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.
 

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