I have a question regarding classes in Python. When I create a new object like this and add it to a variable:
user = User.objects.create(name='The Name')
Can I use that variable to refer to that newly created object? Like this:
print(user.name)
Of course you can. Actually, it's the only way to use newly generated object - if you, for instance, did this:
User.objects.create(name='The Name')
you couldn't access that same object ever again. After that, if you do this:
print(User.objects.create(name='The Name'))
you will create another new object and print its name. So, you basically use variable to store that object you have created.
Related
Learning class in python, using below github(https://github.com/gurupratap-matharu/Bike-Rental-System), I cloned it and I try to add database class. I did it and it works. But I don't think I did it correctly (pythonically or object oriented correctly). Can someone please do a code review? ( https://github.com/isolveditalready/PLAYGROUND ) I am espescailly not sure if using another class's variable in another class( in dbAction.py, line 15)
Basically, I needed to access another class's variable(From class BikeRental class, variable named stock) from dbActionMe class and I didn't know how so I just passed that variable into dbActionMe class.
If code review is not possible, can someone please review below to see what I could have done differently?
db = dbActionMe()
numOfBikes = db.dbRead()
shop = BikeRental(numOfBikes)
customer = Customer()
...
db.dbUpdate(shop.stock)
I am trying to build an online Python Shell. I execute commands by creating an instance of InteractiveInterpreter and use the command runcode. For that I need to store the interpreter state in the database so that variables, functions, definitions and other values in the global and local namespaces can be used across commands. Is there a way to store the current state of the object InteractiveInterpreter that could be retrieved later and passed as an argument local to InteractiveInterpreter constructor or If I can't do this, what alternatives do I have to achieve the mentioned functionality?
Below is the pseudo code of what I am trying to achieve
def fun(code, sessionID):
session = Session()
# get the latest state of the interpreter object corresponding to SessionID
vars = session.getvars(sessionID)
it = InteractiveInterpreter(vars)
it.runcode(code)
#save back the new state of the interpreter object
session.setvars(it.getState(),sessionID)
Here, session is an instance of table containing all the necessary information.
I believe the pickle package should work for you. You can use pickle.dump or pickle.dumps to save the state of most objects. (then pickle.load or pickle.loads to get it back)
Okay, if pickle doesn't work, you might try re-instantiating the class, with a format (roughly) like below:
class MyClass:
def __init__(self, OldClass):
for d in dir(OldClass):
# go through the attributes from the old class and set
# the new attributes to what you need
I have added the dictionary to the object with this:
dict['var1'] = {'value': 'tetsing'}
object.dict = dict
Now I am confused how to access the dictionary in view. Do I use:
object.dict['var1']['value'] or object.dict.var1.value
First of all you should to rename variable and attribute names so that they aren't in conflict with built-in names like dict.
Now, in normal Python code, use the first way.
However, if you are trying to access it from the Django template, use the second one.
This question already has answers here:
How can you dynamically create variables? [duplicate]
(8 answers)
Closed 8 years ago.
I'm just learning to program and am learning Python as my first language. As an exercise I'm trying to write an address book program. New contact are created by the user using the command prompt. New contacts are object instances of the Contacts class.
I know how to instantiate a class object from within the code, but how do I create one with a variable name based on user input? Say I prompt the user for a name -- how do I take that info and use it for the variable name of my new object?
Thanks!!
From the comments, it turns out you are asking about something that gets asked more than once on here. "How can I create dynamically named variables".
Answer: Don't do this. Chances are there are better ways to solve the problem.
Explanation:
If you were to create dynamically named variables, you don't quite have a good handle to them once they are created. Sure there are ways to check the globals and local scopes to see what is there. But the fact is that you should have definitive control over what is being created.
What you should do is put them into a dictionary:
people = {}
name = raw_input("What name? ") # "person"
people[name] = User(name)
print people
# {'person': <User: "person">}
print people.keys()
# ['person']
This way you are not creating arbitrary variables in your namespace. You now have a dictionary of keys and objects as values. It is also a can of worms to allow a user-supplied input to drive the naming of a variable.
For more info, just search on here for the same topic and see numerous examples of why you should not do this. No matter what examples you see showing you how to use globals(), etc, please take my advise and don't go that route. Love and enjoy..and maybe hug and kiss, your dictionary.
References:
How can you dynamically create variables via a while loop?
Is it possible to "dynamically" create local variables in Python? (DONT DO THIS)
You do not make clear why you would want to instantiate objects of which the name is determined as runtime as you wish. It is important to realize that that is not common practice.
It is possible, though, using the setattr builtin:
setattr(someobject, name, user)
Somewhat more normal usage would be to use a dictionary. So if you have more than one user instance and want to store them, you could store them in a dictionary like below. This would allow you to reference the object by name.
class User(object):
def __init__(self, name):
self.name = name
users = {}
name = raw_input("What name?")
users[name] = User(name)
print users
print users['Andre'].name
Sample output:
What name?Andre
{'Andre': <__main__.User object at 0x7f6b418a8710>}
Andre
In the below python code ,can the object know that the template tag is referring a variable and get that in a python variable
newemp is the object that i am passing from the views and the template is trying to access a variable as {{newemp.get_names.emp_add}} ,now in the python code can the object print this variable i.e, emp_add
class Emp(models.Model):
name = models.CharField(max_length=255, unique=True)
address1 = models.CharField(max_length=255)
def get_names(self):
logging.debug(var)
var=self.some referred object
names = {}
No. The access is done once the appropriate object has been returned from get_names() so there is no direct way to know within the method what is being accessed.
If you are asking whether you can write to a variable within a template, and then access that value back within your Python code, I do not believe so. That kind of goes against the idea of templates, IMHO.