This question already has answers here:
How to Create Shared Class Attributes between Classes in Python
(1 answer)
python class instance variables and class variables
(4 answers)
Closed 2 years ago.
Basically I have 1 class object (Let's say Class A), which contains some value assigned to a variable (attribute of class, let's say self.use). There are multiple other classes, (B, C..) and functions creating instance of that class A. I want to share self.use among all the objects of the class A (can be created by any module, any function)
For Example :
class Core(object):
def __init__(self):
self.use = True
if self.use:
main()
def main(self):
# doing some stuff
The above class has an attribute self.use, main function is called based on the value of self.use. Now I have other modules which are using Core class :
class Helper(object):
def func1(self):
self.core = Core()
def func2(self):
self.core = Core()
In above Helper class, I've created 2 objects of Core class. What I want if self.use is to be created only once no matter how many objects are created by any functions.
PS. Please don't tell me to create Core object only once, and not from each function. There are lot of such modules and functions which can not be changed at the moment.
Related
This question already has answers here:
Is it possible to do partial inheritance with Python?
(4 answers)
Closed 8 months ago.
I have a parent class with a lot of methods. I want some of them inherited in all of the child classes. Some of the methods I only want in certain classes. Can I somehow select which methods to inherit. I know I could override them in the child class, but I would prefer a positive approach of adding what you want instead of overriding the ones you don't want.
I am using the backtrader library.
class BaseStrategy(bt.Strategy):
def notify_cashvalue(self, cash, value):
if value < self.starting_cash * self.terminate_threshold:
self.log(f'Stopping strategy at due drop below {self.terminate_threshold * 100}% of initial cash.')
self.cerebro.runstop()
This is the class I want inherit from. As you see parent class is a child class to the library base, but this class implements empty methods.
Methods like notify_cashvalue are always called when this class is used. In my example notify_cashvalue has some attributes that will not be defined in all the child classes, so there would an error as notify_cashvalue is allways called, as are several other functions, which I want to selectively inherit.
I found here Is it possible to do partial inheritance with Python? that you can select the methods you want in this way:
class Class0():
def hello():
return "Hello"
def bye():
pass
def nice():
pass
class Class1():
Hello = Class0.hello
This question already has answers here:
Changing class attributes by reference
(1 answer)
How to change class attributes using a method?
(2 answers)
How to change a class attribute inside __init__?
(2 answers)
Closed 2 years ago.
I have a particular problem with objective python, I would like to have a configuration class (Config), so it could be used as a base class for other classes which will need configuration data. What I want do is to use this Config class to share once iniciated data among all inheriting classes. What is important for me, when class Inherit configuration data I want it to be able to use it as it owns, for ex:
class Config:
a= None
b= None
class A(Config):
def __init__(self):
a = 10
def print_a(self):
print(self.a)
And here is the first questione, how should I set values of a and b in A class? Another one is how to call them inside the class?
When I'm doing sth like this :
obj = A()
obj.a = 5
or when i add methon do A class, which sets a variable:
class A(Config):
def __init__(self):
a = 10
def print_a(self):
print(self.a)
def setA(self, val):
a = val
and call :
obj = A()
obj.setA(12)
it does not change either A.a or Config.a
To sum up, my goal is to create a class with static variables (Config), and through inheritance I would like to obtain acces to those variables from another class A(Config), and use those variables as they were native class variables. It is also important that every change in obj = A() -> obj.a should change Config.a variable (the same when I change variable a insade class A).
Its sucha a confusing idea what I want to do, hope you understand. Also I am pretty new to python so there is a lot of I dont understand yet, try to be forgiving please :).
IGNORE THIS, I MISUNDERSTOOD THE QUESTION, LEAVING OPEN FOR COMMENTS
Well as far as I can see, the problem is the lack of the use of self. In the methods A.setA() and A.__init__, you have to used self.a and thus have simply created a local variable for the method.
So a functioning version of the class A would look like this:
class A(Config):
def __init__(self):
self.a = 10 #As I mentioned, you need this `self.a` rather than just `a`
def print_a(self):
print(self.a) #You got that right
def setA(self, val):
self.a = val #Same here with `self.a`
Think of making a method as simply defining a variable of the function class, and that the method behaves the same as it would outside of a class apart from the additional self argument, which is used to access the attributes of the class.
This question already has answers here:
Python class attribute referencing
(2 answers)
Closed 7 years ago.
Is it possible to access self.bin outside the class?
class kon():
def __init__(self):
pass
def add(self):
con=7
self.bin=100
h=kon()
bin=h.bin
In one topic advised to use self. before variables but it did not work.
Maybe such variables must be in __init__ method.
You have to read docs. It will be very useful for you.
The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named init(), like this:
def __init__(self):
self.bin = 0
When a class defines an init() method, class instantiation automatically invokes init() for the newly-created class instance.
After this you can use this property in you object, to read or assign value.
Also, there is a difference between initialize properties in the class. From the docs:
class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
This question already has answers here:
Adding a method to an existing object instance in Python
(19 answers)
Closed 8 years ago.
Lets say I have a class:
class SomeClass(SomeSuper) :
def __init__(self) :
#some things
But just because the class is generated from somewhere like Qt-Designer .ui to .py I dont want to touch that class, yet I want to add a built in function that is overridden from the class's super class - say:
def closeEvent(self, e)
#some things
Is there a way I can have:
a = SomeClass()
a.closeEvent()
where closeEvent() is outside the class somewhere else and is wired to the class?
What about monkey patching the class?
SomeClass.closeEvent = closeEvent
This question already has answers here:
How to avoid having class data shared among instances?
(7 answers)
Closed 9 years ago.
Look at the code below:
class Node:
feature = list()
label = list()
def __init__(self, f, l):
self.feature.append(f)
self.label.append(l)
I create two instances of this class:
n1 = Node(1,2)
print n1.feature
n2 = Node(3,4)
print n2.feature
My desired output is:
1
2
But the real output is:
1
1 2
What is the problem? How can I fix it?
variables defined in class scope are class variables, and are share among all class instances (they are stored on the class object itself, not on the instances).
Just initialize the variables inside the init function.
class Node:
def __init__(self, f, l):
self.feature = [f]
self.label = [l]
The issue is that you're trying to "declare" the member data for the class instances in the class block. That's not how Python works.
Everything defined in the class block (including feature, label, and __init__) becomes an attribute of the object that represents the class itself, not the instances of the class. Trying to access an attribute that doesn't exist in an instance will fall back to the class, which is how method lookup works.
There is no way to create a attribute on an instance until it exists and you have a reference to it. The purpose of the __init__method is to give you a place to do that. So initial values for an instance's member data should be set up in __init__; trying to declare these initial values in the class block actually does something else.