Excuse me, I am pretty new to oop in python, but I'm wondering how to pass the value of tld_object in gather_site() to the method gather_path()
class MyClass:
def __init__(self):
print "Class Initialized"
def gather_site(self):
tld_object = Tld.objects.filter(id=3)
return tld_object
def gather_path(self):
path_object = PathsOfDomain.objects.filter(FKtoTld=)
models.py
class Tld(models.Model):
##default table PK here.
##fields here
class PathsOfDomain(models.Model):
##default table PK here.
##fields here
FKtoTld = models.ForeignKey(Tld)
Basically is what is happening in table Tld, has a 1:M relationship to PathsOfDomain and I want to be able to get the related paths, based on tld_object which comes from database in gather_site() method
Any help is graciously appreciated. Thank you.
def gather_path(self):
path_object = PathsOfDomain.objects.filter(FKtoTld=3)
I think should work fine ...
class MyClass:
def __init__(self):
print "Class Initialized"
def gather_site(self, id):
# Note I'm using get instead of filter when dealing with PKs.
# Only one object is going to be returned.
self.tld_object = Tld.objects.get(id=id)
return self.tld_object
def gather_path(self):
# At this point you have to have self.tld_object already set,
# Either check it exists or give it a default value.
path_object = PathsOfDomain.objects.filter(FKtoTld=self.tld_object.id)
Related
I want a program to call a specific class based on a parameter/variable value. However, I don't want to use any clunky if-statements. My first thought was to use the globals() function, but I couldn't get it to work. Here's an example:
class SomeClass:
def __init__():
print("Hello, world!")
class OtherClass:
def runClass(className):
# Call class based on variable className
The reason I want to do this is because there is a wide variety of classes may need to be called, and so just piling up if-statements in my code won't do it. Any help would be greatly appreciated. Thanks!
Here's how you can call a class via globals
class SomeClass:
def __init__(self):
print("Hello, world!")
def __call__(self):
return "SomeClass called"
class OtherClass:
def runClass(self, className):
globals()[className]()()
o = OtherClass()
result = o.runClass("SomeClass")
print(result)
Notice, I am instantiating and then calling it via the __call__ special method, which is the closest match to your description I could think of.
Use a dict.
name_to_class = dict(some=SomeClass,
other=OtherClass)
def factory(name):
klass = name_to_class(name)
return klass()
some_obj = factory("some")
other_obj = factory("other")
One way to solve this problem is to use a dictionary to map the values of the variable className to the corresponding class.
Try this exemple :
class SomeClass:
def init(self):
print("Hello, world!")
class OtherClass:
def init(self):
print("Goodbye, world!")
classNameToClass = {
"SomeClass": SomeClass,
"OtherClass": OtherClass
}
def runClass(className):
# Call class based on variable className
cls = classNameToClass[className]
return cls()
runClass("SomeClass") # prints "Hello, world!"
runClass("OtherClass") # prints "Goodbye, world!"
Here, the dictionary classNameToClass maps the string names of the classes (e.g. "SomeClass") to the corresponding class objects (e.g. SomeClass). Then, in the runClass function, we look up the class object using the value of the className variable, and call it to create an instance of the class.
I've found an answer. The parameter that governs the called class can just be assigned elsewhere. At first, I thought it would need some complex function, but in reality, I guess the question didn't give enough details. The class itself only uses items from whatever object is given. So, instead of having to dynamically call a class, it's as simple as:
class SomeClass:
def printHelloWorld():
print("Hello, world!")
class OtherClass:
def __init__(self, usingClass):
self.object = usingClass
def doThis():
usingClass.printHelloWorld()
x = OtherClass(SomeClass())
x.doThis()
It's on me for not giving enough information. Thank you all for your help.
I have a class called resources and I have defined one method called get_connect. I want to use the data of which get_connect returns to the other classes. I need at least three classes and I use the data of get_connect and I have to parse that data. To implement this I have written the code below
class resources:
#staticmethod
def get_connect():
return 1 + 2
class Source1(resources):
def __init__(self):
self.response = resources.get_connect()
def get__details1(self):
print(self.response)
class Source2(resources):
def __init__(self):
self.response = resources.get_connect()
def get_details2(self):
print(self.response)
class Source3(resources):
def __init__(self):
self.response = resources.get_connect()
def get__detail3(self):
print(self.response)
source1 = Source1()
source2 = Source2()
source3 = Source3()
source1.get__details1()
source2.get_details2()
source3.get__detail3()
But the problem with the code is for every class in init method I am calling the get_connect method. I don't want to repeat the code. I need help for avoiding redundancy which I have asked below
Is there any way I can call get_connect in one place and use it for other classes maybe a decorator or anything? if yes how can I?
While creating objects also I am calling each class and calling each method every time. is there a way to use any design pattern here?
If anyone helps me with these oops concepts it will be useful.
First of all, is there any reason why you are using get_connect method as static?
Because what you can do here is declare it in the parent class:
class resources:
def __init__(self):
self.response = self.get_connect()
def get_connect(self):
return 1 + 2
This way you do not need to define the __init__ method on every class, as it will be automatically inherited from the parent.
Regarding the second question, it really depends on the context, but you can use a strategy pattern in order to retrieve the class that you require to call. For this rename the method of get details into the same for each of the classes, as basically they're used for the same purpose, but changed on the context of the class implementation:
class Source1(resources):
def get_details(self):
print(self.response)
class Source2(resources):
def get_details(self):
print(self.response)
class Source3(resources):
def get_details(self):
print(self.response)
classes = {
"source_1": Source1,
"source_2": Source2,
"source_3": Source3
}
source_class = classes["source_1"]
source = source_class()
source.get_details()
Hope this helped!
I want to have a class that is used just for accessing read-only data. If the data is requested from the class but does not exist yet, I want the class to handle getting the data. I'm just wondering if the following code makes sense; can you see any potential issues with this?
class Data:
#property
def some_data(self):
if hasattr(Data, "_some_data"):
return Data._some_data
else:
Data._some_data = function_that_gets_data()
return Data._some_data
# other definitions for more data go here ...
D = Data()
# access data
print(D.some_data)
I'm doing basically this exact thing in my code base and it's been working great for me, it's been a great way of caching information.
class ItemBase(BaseClass):
_soup = None
#property
def soup(self):
if not self._soup:
self._soup = get_info()
return self._soup
I have a property with a docstring, but I can't seem to access that using help().
I tried the following two ways of accessing it:
class Mini(object):
#property
def t(self):
""" ahhhh """
return 0
x = Mini()
help(x.t)
class MiniNew(object):
t = property(doc='This is a doc')
y = MiniNew()
help(y.t)
The first help returned Help on int object: blahblahblah and the later one returned AttributeError: unreadable attribute.
What is the right way to access the doc of a property?
You need to access the property from the class. When accessed from an instance, it acts like the returned value, which is not the thing you documented.
class Example(object):
#property
def value(self):
"""help text"""
return 1
help(Example.value)
This will print:
Help on property:
help text
I have a UserModel class that will essentially do everything like login and update things.
I'm trying to pass the instance of itself (the full class) as an argument to another function of another class.
For example: (obviously not the code, but you get the idea)
from Car import CarFactory
class UserModel:
def __init__(self,username):
self.username = username
def settings(self,colour,age,height):
return {'colour':colour,'age':age,'height':height}
def updateCar(self,car_id):
c = CarFactory(car_id, <<this UserModel instance>>)
So, as you can see from the very last line above I would like to pass an instance of UserModel to the CarData class, so when within the CarData class I can access the UserModel.settings(), however, I am unsure of the syntax. I could of course just do:
c = CarFactory(car_id,self.settings)
Any help would be grateful appreciated.
Thanks
c = CarFactory(car_id, self)
doesnt work?
on a side note it would be self.settings() not self.settings ... unless you define settings to be a property