How to get class instanced using variable inside of the class - python

I am trying to access a class instance. I can't assign the class to a variable when I load it and then use it because I need to access the class based on what the user enters.
i.e: user goes to link website.com/classes/y, I need to access the instance with the name y.
I already handle the link and can get "y" or whatever the user entered by itself.
I have the class code as follows:
class LoadModel:
existing_models = []
def __init__(self, model_path):
self.name = model_path.parent.name
self.__class__.existing_models.append(self.name)
For now, I can verify if the class exists using the existing_models list, but how will I be able to access it using the self.name?
I want to access it using LoadModel.name.

It sounds like you want to keep a dictionary of model names to instances. You could do that with something like:
class LoadModel:
modelsByName = {}
def __init__(self, model_path):
self.name = model_path.parent.name
self.modelsByName[self.name] = self
Furthermore if you wanted to access an instance named name as LoadModel.name you could could add
setattr(self.__class__, self.name, self)
to __init__. Or if you were looking up by string (which it sounds like you might be) then you would just do LoadModel.modelsbyName[name].
Note also that you don't need to use self.__class__ when accessing members of the class that you have not assigned within the instance, and since you're only accessing the dictionary object defined in the class, you can use the reference inherited by the instance (self.modelsByName) instead of accessing the class explicitly (self.__class__.modelsByName).

Related

When to use self and when not to use self

Which class option is preferable and why?
Option 1
class Person():
def __init__(self):
pass
def sayHello(self, name):
print "{} says hello!".format(name)
def driver(self):
for name in names: # names is generated in the driver function by some means of input
self.sayHello(name)
Option 2
class Person():
def __init__(self):
self.name = None
def sayHello(self):
print "{} says hello!".format(self.name)
def driver(self):
for name in names: # names is generated in the driver function by some means of input
self.name = name
self.sayHello()
You can assume that there are more variables than just name and that multiple functions are using these variables. The main point I am trying to make is that the variable value's are changing inside the for loop
Even though your exemple is syntaxically correct, it doesn't help at all understand your question regarding how to use a instance attribute.
From want I'm guessing, there's two questions :
When to use a class method (def foo(self, bar)) ?
When to use a instance attribute (self.name) ?
Instance attribute should be used when you need to "share" a variable between functions or retrieve it from outside a function. That variable will be "attached" to the object (for exemple, the color of a car, the nickname of a user, ...)
If your function / method need to call this kind of variable, it must use self to get it, so you have to set it as the first argument when defining this function.
If you just need a temporary variable to loop over it and do some stuff, you don't need to use a class method, a simple function will do the trick.

Python inner class variable, namespace

class myouterclass(object):
def __init__(self,ID):
self.myouterclassID=myouterclassID
self.myinnerclass=self.MYINNERCLASS()
class MYINNERCLASS:
def __init__(self):
self.myinnerclassID=myinnerclassID
I am trying to create an inner class and create some variables including an ID. For simplicity I would like to also use ID to define different instances of my outer class as well.
I am lacking some understanding on what I am doing wrong.
What I am trying to accomplish is to use the same name variable "ID" to define an identification for the different instances of the outer class AND also to use the same name variable "ID" to keep track of the different instances of the inner class object "myinnerclass". I am planning to create more than one instances of the innerclass and I need to have different ID to keep track of them
Thanks
Maybe you wanted that?
class myouterclass(object):
def __init__(self, the_id):
self.myouterclassID = the_id
self.myinnerclass = self.MYINNERCLASS(the_id)
class MYINNERCLASS:
def __init__(self, inner_id):
self.myinnerclassID = inner_id
def __init__(self, inner_id):
self.myinnerclassID = inner_id

What does append(self) mean in Python classes?

I am new to OOP in Python and working on inheritance concept. I came across the following code:
class ContactList(list):
def search(self, name):
'''Return all contacts that contain the search value in their name.'''
matching_contacts = []
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
return matching_contacts
class Contact:
all_contacts = ContactList()
def __init__(self, name, email):
self.name = name
self.email = email
self.all_contacts.append(self)
I'm wondering why do we use self.all_contacts.append(self) and how does for contact in self work ?. If I understood correctly, self appoints to the instance of a class (object), and appending to a list is not trivial to me.
all_contacts is a class variable -- it is unique to the class, not to each instance. It can be accessed with Contact.all_contacts. Whenever you create a new contact, it is appended to this list of all contacts.
ContactList inherits from list, so for contact in self works the same way as for i in [1,2,3] -- it will loop through all the items that it contains. The only thing that it does differently from a list is implement a new method, search.
Well, basically you create a list of Contact and appending self add the current contact in the all_contacts list.
Now for your questions,
I'm wondering why do we use self.all_contacts.append(self)
We would use that because all_contacts is a class variable which means that the list will be shared among all Contact instances.
how does for contact in self work?
Well, as you said, since self represents the current instance, calling for contact in self is allowing you to iterate on the current Contacts list.
In other words, your code sample let you create Contact instance which is appended in a class variable (shared) automatically. Now, by providing a ContactList class that inherits from list, they allow you to use the implemented search method which will return you another list of Contact based on your search filter.
all_contacts is a class variable of Contact, initialized as an instance of ContactList, a subclass to list, so when a new Contact instance is instantiated via the __init__ method, self is assigned with the new instance being instantiated and self.all_contacts.append(self) would add the new Contact instance to the all_contacts list. This way, Contact.all_contacts will maintain a list of all Contact instances that have been instantiated.

Python, why do we have to inherit from 'list' class

I'm learning object oriented python and came across this issue where python is forcing me to inherit from built-in 'list' class to use append method.
class ContactSearch(list): #Why inherit from 'list'?
def search(self, name):
matching_contact = []
for contact in self:
if name in contact.name:
matching_contact.append(contact)
return matching_contact
Why can't I simply declare an empty list and append to it? For example it works find in the following code without inheriting from 'list class':
class Contact:
all_contacts = []
def __init__(self, name, email):
self.name = name
self.email = email
Contact.all_contacts.append(self)
In ContactSearch, matching_contact is temporary variable for result of searching. A instance of ContactSearch is list. So search method can use self in iterator. matching_contact is over when search method is done.
In Contact, all_contacts is class variable and all instance of Contact share this. Instance of Contact is NOT list. But you can access all contact using like Contact.all_contacts, and yes, it is list.
The difference is only where the data is stored. The one stores data in itself, and the another stores data in its variable.

Can a class variable be an instance of the class?

Can a class variable of say, class Foo be a Foo object itself?
For example, I'm trying to build a class for the finite field of order 11, and I want a chosen generator (2) to be associated with this class an instance.
What I have in mind:
class FiniteField11:
generator = FiniteField11(2)
def __init__(self, element):
self.elt = element
This does not compile; I have a NameError: name 'FiniteField11' is not defined.
I realize that there is a chicken-or-egg first problem here, but is there a way to achieve what I want?
Apologies if this is a duplicate, but I can't find one.
You can do something like this:
class FiniteField11:
def __init__(self, element):
self.elt = element
FiniteField11.generator = FiniteField11(2)
Your code fails because FiniteField11 was not defined when the class defintion was parsed.
Yes it can, but the name doesn't exist until the class statement finishes. Therefore, you have to set this class variable after creating the class, perhaps just below the class block or in the instance initializer.

Categories

Resources