Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I invoke a python class in my python file. The python class I invoked will load big data from disk.
# invoke python class
import mypythonclass
def method():
for i in range(100):
mypythonclass.dosomething(params)
# code in mypythonclass
def dosomething(params):
# load data here
# do something
My question is how can I avoid load data repetitively in mypythonclass, thanks.
If the data you are loading will be used by the class instance, you may initialize the data when instantiating the class.
For example:
class MyPythonClass(object):
def __init__(self, data):
self.data = data
def dosomething(self, params):
# use self.data
If possible you should move the class instantiation out of the for loop, so the data is loaded only once. But the example you provided, doesn't have sufficient details, so it is know exactly what you want.
If the data does not change across different instances of the class, you can use class attributes and make dosomething a class method.
class MyPythonClass(object):
data = some_data
#classmethod
def dosomething(cls, params):
# use cls.data
In this case, the data will be available by all the instances of the class.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 months ago.
Improve this question
So I am working on an implementation of a Dynamic Decision Network (DDN) class.
This DDN is a type of Bayesian Network (BN) with some additional functionality.
However, I also defined a Quantum Bayesian Network (QBN), that uses quantum computing to perform inference. Its implementation is very similar to the BN class, I only change one of the BN methods to perform quantum computations instead (the query method) and add some other methods just to help perform these computations.
I want the DDN class to be able to inherit from the BN class if one wants to perform the computations classically, and inherit from the QBN class if one wants to perform the computations in a quantum manner.
The code looks something like this:
class BN:
...
def query(self, ...):
...
class QBN(BN):
...
def query(self, ...):
# Modified query method
...
class DDN(???):
...
Am I structuring the hierarchy wrong in some way? How can I reconcile this?
You can put the class into a factory function:
def make_DDN(Base):
class DDN(Base):
def other_methods(self):
...
return DDN
Now you can make new classes:
DDN1 = make_DDN(BN)
etc
The working field of your program is unclear to me, and it is unclear what objects and their methods should be able to do, so this is a suggestion, not an answer. But it's too big for a comment.
class BN:
def method(self):
return self.data*2
class QBN(BN):
def method(self,classic=False):
if classic:
return super().method()
return self.data*3
class DDN(QBN):
def __init__(self,data):
self.data=data
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
This post was edited and submitted for review 23 days ago.
Improve this question
I recently stumbled upon a problem, How do i access a class's instance variables (aka the variables inside __init__) from outside/inside the file without creating an instance of a class (i.e main = main.foo()).
Example:
class foo:
def __init__(self,name):
self.name = name
class bar:
os.mkdir(foo.name)
you can set the variable as global, and then you will be able to access this variable from everywhere. and also modifying it.
Not sure why you are using nested classes, but:
foo_name = None
class main:
class foo:
def __init__(self,name):
global foo_name
foo_name = self.name = name
class bar:
def __init__(self):
print(foo_name)
main.foo("Jonathan")
main.bar()
Prints out "Jonathan"
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Below two variants to initialize a class instance variable. What is the best practice for initializing an instance variable in a class in python and why (maybe none of the suggested variants)?
Assumption: variant a because it might be more explicit?
class Example():
def __init__(self, parameter):
# EITHER
# variant a to initialize var_1
self.var_1 = self.initialize_var_1_variant_a(parameter)
# OR
# variant b to initialize var_1
self.initialize_var_1_variant_b(parameter)
# OR something else
# ...
def initialize_var_1_variant_a(self, parameter):
# complex calculations, var_1 = f(parameter)
result_of_complex_calculations = 123
return result_of_complex_calculations
def initialize_var_1_variant_b(self, parameter):
# complex calculations, var_1 = f(parameter)
result_of_complex_calculations = 123
self.var_1 = result_of_complex_calculations
example_instance = Example("some_parameter")
print(example_instance.var_1)
Variant A is the common way to do this. It is very nice to be able to see all of the class members by looking at __init__, instead of having to dive into the other functions (initialize_var_1_variant_b) to find out exactly what attributes are set.
In general, all member attributes that a class will ever have should be initialized in __init__.
To come at it from another angle, initialize_var_1_variant_a should do as little as possible. Calculating the value of var_1 and saving it as a class attribute are two tasks that can be easily broken apart.
It also opens up the possibility of moving initialize_var_1_variant_a outside of the class itself, so it could be re-used by other parts of your program down the line.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I want to create a service class that just has one instance, so should I make that class a singleton, or should I make the methods as classmethods?
class PromoService():
#classmethod
def create_promo(cls, promotion):
#do stuff
return promo
class DiscountPromoService(PromoService):
#classmethod
def create_promo(cls, promo, discount):
promo = super(DiscountPromoService, cls).create_promo(promo)
promo.discount = discount
promo.save()
return promo
The reason I don't want to create it as a module is because I would need to subclass my service. What is the most pythonic way to do this, the above-mentioned way or to make a singleton class?
Short answer: In my opinion it would work.
BUT, In pure pattern's sense, I have been wrestling with this question for a while:
Do python class methods and class attributes essentially behave like a Singleton?
All instances of that class have no bearing on them
Only class itself have access to them
There is always one of them
Yes, pure Singleton Pattern comparison would fail plain and simple but surely its not far off?
Wouldn't call myself a python expert, so happy to know views on this be corrected on my assumptions.
If you want a singleton, go with a singleton. The pattern referenced here works well. You would simply need to do something like:
class PromoService():
__metaclass__ = Singleton
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
This is incredibly noobish, but here's an example of what I want:
class A:
def __init__(self):
self.m_file = file() # name required
self.m_file = None # readonly attribute error
self.m_file = "" # readonly attribute error
def ButtonPressed(self):
self.m_file = open(tkFileDialog.askopenfilename(), 'r')
None of the attempts in __init__ work. I tried searching for python init variable as file but those keywords brought out a lot of posts not answering the question.
As noted in the comments, the open() function in ButtonPressed method will overwrite anything done in the __init__ call. I would recommend keeping this line
def __init__(self):
self.m_file = None
As this will allow you to check whether the variable is None before attempting to use it somewhere else in the class
You probably want to use the open() method. I don't think that you'd want to do this in your constructor, but open() is what you're looking for.