Is there an anonymous call of a method in Python?
<p>This is my database manager class:</p>

<pre><code>class DatabaseManager(object):
    def __init__(self):
        super().__init__()
        self.conn = sqlite3.connect('artist.db')
        self.c = self.conn.cursor()

    def create_table(self):
        self.c.execute(
            'CREATE TABLE IF NOT EXISTS artists(title TEXT, artist TEXT, album TEXT, year INTEGER, '
            'genre TEXT, ext TEXT, path TEXT, art TEXT )')
        self.c.close()
        self.conn.close()

    def insert(self, song):
        self.c.execute(
            'INSERT INTO artists(title, artist, album, year, genre, ext, path, art) VALUES(?, ?, ?, ?, ?, ?, ?, ?)',
            (song.title, song.artist, song.album, song.year, song.genre, song.ext, song.path, song.art))
        self.conn.commit()
        self.c.close()
        self.conn.close()

    def retrieve_all(self):
        self.c.execute('SELECT * FROM artists')
        data = self.c.fetchall()
        self.c.close()
        self.conn.close()
        return data
</code></pre>

<p>There are more methods but this is not important. When i start the app i call <code>create_table()</code> and when i need some database action i create another obect(or remake the past one) to call <code>insert</code> for example.</p>

<pre><code>    db = DatabaseManager()
    print(db.retrieve_artist('asdf'))
    db = DatabaseManager()
    print(db.retrieve_all())
</code></pre>

<p>Is there any way to avoid this? In Java there is anonymous calls:
<code>new DatabaseManager().retrieve_artist("asdf")</code>
Is anything similar possible in Python?</p>

<p>As @Remcogerlich said, you are assigning the instantiation to a variable. If you just don't do so, you can approach what you want.</p>

<pre><code>DatabaseManager().retrieve_artist('asdf')

AnyOtherClass().callAnyMethod()

# both disappeared 
</code></pre>

<p>In this way, Python executes the instantiation, calls the method you want to, and since you don't tell it to assign to any variable, it "<em>disappears</em>".</p>

<p>You may even do that with class functions, like this:</p>

<pre><code>ClassWithClassMethods.callAnyClassMethod()
</code></pre>

<p>However, I wouldn't recommend you to work with that on that way. Normally, database connections are established as an instantiation, used as long as you need to, and when you don't need them anymore you close them <em>safely</em>. I think you are not doing that there, and are wasting memory usage, I guess (anyone correct me if I'm wrong). It's easier that you create an object for each time you want to use the database for long, and once you finish in that piece of code, you close the connection and remove the object.</p>

python python-2.7 python-3.x