Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addressing instance name string in __init__(self) in Python

I am doing something like this:

class Class(object):
    def __init__(self):
        self.var=#new instance name string#   

How do I make the __ init __ method of my instance to use the instance name string for 'c'? Say in case:

c=Class()

I want c.var equal to 'c'.

Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

c=Class()

Then, suppose:

del c

Later on:

c=Class()

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.


Thanks for your replies, I am implementing persistence and Class is persistent object's class. I want __ init __ to add an entry to the database when:

c=Class()

Then, suppose:

del c

Later on:

c=Class()

sholuld create an instance using data from database if there already is an entry 'c', otherwise create new entry.

like image 963
Alex Avatar asked Dec 04 '22 16:12

Alex


2 Answers

Python doesn't have variables, it has objects and names. When you do

c = Class()

you're doing two things:

  1. Creating a new object of type Class
  2. Binding the object to the name c in the current scope.

The object you created doesn't have any concept of a "variable name" -- If later you do

a = c

then the same object is accessible in exactly the same way using the names a and c. You can delete the name a, and the object would still exist.

If the objects you create need to have a name, the best way is to pass it to them explicitly,

class Class(object):
    def __init__(self, name):
        self.name = name

var = Class('var')
like image 53
dF. Avatar answered Dec 21 '22 03:12

dF.


You can't do this. The reason for this is that the object of the class is created first, and only afterwards is this object bound to the name of the instance.

like image 31
sykora Avatar answered Dec 21 '22 05:12

sykora