I'm doing a database insert script in pycassa. I want to set up a public static class that defines some variables that will get used a lot by other functions later on. Heres what I have...
class ks_refs():
pool = ConnectionPool('TweetsKS')
user_name_cf = self.cf_connect('UserName')
user_tweet_cf = self.cf_connect('UserTweet')
def cf_connect(column_family):
cf = pycassa.ColumnFamily(self.pool, column_family)
return cf
I haven't even tried to run this yet because I'm sure it wont work. You can see I want this static variable 'pool' first, and then set up user_name_cf and user_tweet_cf (and some more later) using the cf_connect method which needs 'pool' to work.
I know I could put that method outside the class, or I could have this non-static and make an instance of it, but I want to try this because this is what I really want (before I was just using globals but I think a static class holding all this is the best idea)
I think you want to have a class method instead:
#classmethod
def cf_connect(cls, column_family):
cf = pycassa.ColumnFamily(cls.pool, column_family)
return cf
Now you can refer to the pool defined on your class with ease.
Your user_name_cf and user_tweet_cf 'attributes' will not work, however. You can add these after having created the class definition:
class ks_refs():
pool = ConnectionPool('TweetsKS')
#classmethod
def cf_connect(cls, column_family):
cf = pycassa.ColumnFamily(cls.pool, column_family)
return cf
user_name_cf = ks_refs.cf_connect('UserName')
user_tweet_cf = ks_refs.cf_connect('UserTweet')
where they are then module-level constants, or you can add them to the class as attributes after the fact:
ks_refs.user_name_cf = ks_refs.cf_connect('UserName')
ks_refs.user_tweet_cf = ks_refs.cf_connect('UserTweet')
Related
I encountered a simple issue in Django, there were similar questions on this forum but haven't answered correctly so i'm writing it again.
My issue is just same as this question. How to instantiate a class just after starting Django server and access its members later in views.py
I have to instantiate custom class when server is starts, and should integrate in the view by accessing methods of instantiated custom class.
Let's say we made this class and instantiated when server starts and stored to variables that can be used in later like in urls.py or somewhere. (I don't know how)
class MyClass:
def __init__(self):
self.a=3
def foo(self):
return self.a
...
#When django server starts
new=MyClass()
In the view.py, let's say that there is some magic that passes instantiated instance as a parameter in view's method.
def index(request, instantiatedClass :MyClass):
a=instantiatedClass.foo()
return HttpResponse(f"{a} is your var.")
This is what I want. but I investigated and in the urls.py there is no options that can passes custom parameters to pointed views.py's method other than passing url information by the user.
I believe that Django's model behave and instantiated not same way like ordinary class.
So how can I achieve this?
Everything you declared outside the functions in views.py will be initiated after you start your server only once. In this case your new variable will be an instance of MyClass and it will be stored in the RAM, once you restart your server, it's data will be lost.
any_views.py
class MyClass:
def __init__(self):
self.a = 3
def foo(self):
return self.a
new = MyClass()
def index(request):
a = new.foo()
print(a)
return HttpResponse(f"{a} is your var.")
I am programming a bokeh application. I want to split the functionalities into different files. But I want to have some attributes accesible from every class, these attributes should be shared and always updated. For example an attribute which stores a dataframe that all the plots are going to use. So I think I have at least two possible solutions:
Use a big class and include the attributes and methods of other files:
class Bigclass(object):
from bk_plots import p1, p2, p3
from bk_data import d1, d2, d3
from bk_layout import ly1, ly2
from bk_events import ev1, ev2
# unfortunately, "from classdefn import *" is an error or warning
num = 42 # add more members here if you like
Note: this solution was copied from here (partial classes)
Or I could use inheritance. The parent will have the shared attributes. The perk of this system is that I would need to send the rest of the object references to every subclass
class Parent():
shared = 'parent'
class Plot(Parent):
def __init__(self):
Parent.shared = 'plots' # update class variable from this class
# I would need to have references to the objects of other classes
class Data(Parent):
def __init__(self):
Parent.shared = 'second'
# [...]
Is there a better way to do this? Which option will bring me less problems?
Finally I have created an my_bokeh_app folder. There I have an __init__.py file with this content for the initialization:
from my_bokeh_app.bokeh_data import BokehData
from my_bokeh_app.bokeh_plots import BokehPlots
from my_bokeh_app.bokeh_table import BokehDataTable
from my_bokeh_app.bokeh_events import BokehEvents
from my_bokeh_app.bokeh_layout import BokehLayout
BokehData()
BokehPlots()
BokehDataTable()
BokehEvents()
BokehLayout()
I have created a Class to share data among all the objects. This is the class:
class BokehSharedData(object):
# ------------------- CLASS VARIABLES ---------------------- #
# This variables are shared. So all the children can access them
data_source = None
bk_layout = None
bk_data = None
bk_plot = None
bk_table = None
bk_events = None
In every class I make a reference to the BokehSharedData class. I also inherit from that class to access to the class variables.
from my_bokeh_app.bokeh_shared_data import BokehSharedData
class BokehData(BokehSharedData):
def __init__(self, **kwargs):
self.env = BokehSharedData
self.env.bk_data = self
# If for example I want to access to the source attribute from the rest of objects
# I could make this shortcut on the shared class
self.env.data_source = ColumnDataSource(...)
def update_data_source(self):
# [...]
And I could read the shared attributes or execute methods from other object:
from my_bokeh_app.bokeh_shared_data import BokehSharedData
class BokehPlots(BokehSharedData):
def __init__(self, **kwargs):
self.env = BokehSharedData
self.env.bk_plots = self
# I could use self.env.data_source here or run some method of BokehData class like this
self.env.bk_data.update_data_source()
The complete app where you can see all the classes working is here
I run into a situation, where I call a static method of a class from another static method. To be sure, that I don't ask an X-Y-question, I'm trying to give some background.
I have a class, that holds a data container and several methods to convert data inside the container. As I also want the converters to be callable from the outside without a class instance, I choose static methods:
class SomeClass(object):
def __init__(self,some_data):
self.data = some_data
#staticmethod
def convert_1(data_item):
return 1+data_item
#staticmethod
def convert_2(data_item):
return 2*data_item
Now I can do SomeClass.convert_1(data_item) without the need to create an instance of SomeClass.
Let's say, I want to have a method inside SomeClass, that does the two converts successively, and also want to have that method as a static method.
Can I do
#staticmethod
def combined_convert(data_item):
data_item = SomeClass.convert_1(data_item)
data_item = SomeClass.convert_2(data_item)
return data_item
inside SomeClass? This feels wrong, as I call the class inside its own definition, but I cannot come up with another 'more pythonic' way.
You can create a class method.
#classmethod
def combined_convert(cls,data_item):
data_item = cls.convert_1(data_item)
data_item = cls.convert_2(data_item)
return data_item
I am using python 2.7 and confused about inheritance concept.
I want to make a script that can download from various manga (japanese comic site)
Every manga site uses a different method to save their file. So i have a "Manga_site" class and class called "mangacanblog" (this is a website manga).
Every manga site has a: homepage,collection,page,etc. and it's all different for each site. my question is. is this script correct to store those homepage,collection_page,etc variable? or should I use self.homepage in mangacanblog class and not in the Manga_site class?
class Manga_site:
def __init__(self,homepage,collection_page,base_manga_page,manga_title = ""):
self.homepage = homepage
self.collection_page = collection_page
self.base_manga_page = base_manga_page
self.manga_title = manga_title
class Mangacanblog(Manga_site):
def __init__(self,manga_title):
homepage = bloglink
collection_page = collectionpagelink
manga_title = manga_title.lower()
base_manga_page = basepagelink
In your Mangacanblog's __init__() function you are just setting local variables homepage, collection_page, etc, not instance variables, to make them instance variables you have to use self. , and this needs to be used in both super class as well as subclass.
But a better thing to do would be to call super(Manga_site).__init__() to let the super class handle its initialization, and then you can initialize sub class just the way you want to.
But for this, you would need to define Manga_site as a new style class, by inheriting from object class. Example -
class Manga_site(object):
def __init__(self,homepage,collection_page,base_manga_page,manga_title = ""):
self.homepage = homepage
self.collection_page = collection_page
self.base_manga_page = base_manga_page
self.manga_title = manga_title
class Mangacanblog(Manga_site):
def __init__(self,manga_title):
super(Mangacanblog, self).__init__(bloglink, collectionpagelink, basepagelink, manga_title.lower())
I have guessing you would define bloglink and collectionpagelink , before you use them in the subclass.
But this given, from the example you have given, what you are trying to achieve may be to use objects of class, and not inheritence.
Inheritence is used when the subclass has extra attributes/properties and extra methods.
You create different objects of same class if you want to store different data in them. Example -
class Manga_site:
def __init__(self,homepage,collection_page,base_manga_page,manga_title = ""):
self.homepage = homepage
self.collection_page = collection_page
self.base_manga_page = base_manga_page
self.manga_title = manga_title
mangacanblog = Manga_site('<homepage url>','<collection_page>',....)
anothermangasite = Manga_site('<another url>',....)
Then you can use these objects anyway you want to.
I've got:
class ArticleController(SubbaseController):
def view(self):
c.referral = self.detect_referral.referrer
return render('/article.mako')
#staticmethod
def detect_referral():
referrer = request.META.get('HTTP_REFERRER', '')
I'm trying to reference the referrer inside of the view action from the detect_referral static method, but I keep getting: 'function' object has no attribute 'referrer' instead. Any ideas?
Also, is that the correct way to get the referrer?
You aren't returning the referrer from detect_referral, and detect_referral is not a property, so you cannot use that syntax.
class ArticleController(BaseController):
def view(self):
c.referral = self.detect_referral()
return render('/article.mako')
#staticmethod
def detect_referral():
return request.META.get('HTTP_REFERRER', '')
It's a local variable inside detect_referral(), and as such its lifetime is limited to the execution time of the method. Before the method is called and after the method returns local variables simply don't exist. (You don't even seem to call the method, so the local variable exists at no time of the execution of your program.)
Most probably you don't want a static method here. (You almost never want a static method in Python. I cannot remember that I ever used one.) Maybe all you need is a class attribute:
class ArticleController(SubbaseController):
referrer = request.META.get('HTTP_REFERRER', '')
def view(self):
c.referral = self.referrer
return render('/article.mako')
Note that the class body is executed once at class definition time.