Changing an instance variable from another class
var_1
is an instance variable, so you need to use the instance:
class test1:
def __init__(self):
self.var_1 = "bob"
instance2 = test2(self) # <<<<<< pass test1 instance
def change_var(self, new_var):
print(self.var_1) #should print "bob"
self.var_1 = new_var #should change "bob" to "john"
print(self.var_1) #should print "john"
class test2:
def __init__(self, t1obj): # <<<< take test1 instance
t1obj.change_var("john") # <<<< use test1 instance
instance = test1()
Gives:
bob
john
How to store a variable of an instance of a class in an instance of another class
Ok first off I see an issue with Your code:
def store_x(self, var):
var.x = self.x
It Needs to be changed to :
def store_x(self, var):
self.x = var.x
This is because whatever you send in the 'var' parameter will only be a copy of whatever you actually passed. And then its scope will only last to the end of that store_x method. So instead you pass that copy and tell your variable class instance to store it inside it's x value.
As for the error you got with:
self.x = None # inside your Model class
I'm not sure why, as I tried the following and it runs fine:
class Variables:
def __init__(self):
self.data = data
self.number_of_clusters = number_of_clusters
self.neighbourhood_size = neighbourhood_size
self.variables_before = None
self.variables_now = None
self.ofv_before = None
self.ofv_now = None
self.x = None
So I'm updating my answer with a deeper example after getting clarification on what is needed. Here are two skeleton classes named 'Variables', 'Model', respectivly:
class Variables:
def __init__(self):
self.data = None
self.number_of_clusters = None
self.neighbourhood_size = None
self.variables_before = None
self.variables_now = None
self.ofv_before = None
self.ofv_now = None
self.x = None
def get_x(self,modelx):
self.x = modelx
class Model:
def __init__(self):
self.x = ({}, {})
# create your class instances here
newVar = Variables()
newModel = Model()
# one way to assign your Variable class's x attribute the tuple dict in question.
newVar.x = newModel.x
# alternate way is to create a function inside your Variable class that updates the x variable based on the argument you send it.
newVar.get_x(newModel.x)
Access instance variable from another class
Just inherit and user super
to call the parent initializer:
class DailyOrders:
def __init__(self, day):
self.orders = []
# ...
class EggOrder(DailyOrders):
def __init__(self, day, eggs=0, name=""):
super().__init__(day)
# Now self.orders is available.
Keep in mind that if the parent initializer receives any parameter, the child must receive it as well in order to be able to pass it.
Not providing a day param ...
If you don't want to provide a day param you should have another class with the interface/functionality that's common to the others, and the inherit from such base class:
class BaseOrders:
def __init__(self):
self.orders = []
# ...
class DailyOrders(BaseOrders):
def __init__(self, day):
super().__init__()
# Now self.orders is available.
self.day = day
# ...
class EggOrder(BaseOrders):
def __init__(self, eggs=0, name=""):
super().__init__()
# Now self.orders is available.
Best way to access variables from another class?
In general there are 2 ways to access a variable from another class:
- You create an object of that class. Then this object has all the variables from the scope of that class assigned to it. For example:
Test t = new Test();
t.name = "test";
- You can also create a static variable. Then the variable is assigned to the class not the object of that class. This way you will not need to create an object, but all instances of the class will share the same variable.
//In the scope of the class
static String name;
-------------------------
//when classing the class
Test.name = "The Name of the Test";
If you do not want to create a new instance of a class every time, and always use the same instance, you can create a singleton object. You write a getter method that gets you the object. It looks like this:
public class Test {
Test t;
public static void main(String[] args) {
t = new Test();
}
public Test getTest() {
if (t != null) {
return t;
} else {
t = new Test();
return t;
}
}
}
I see you work with a JFrame. Then you will probably want to make it a singleton. Else you will open a new instance of the JFrame every time you call upon it, which is not recommended.
Does this answer your question?
Related Topics
How to Pad a String With Leading Zeros in Python 3
Python - How to Separate Paragraphs from Text
What Is the Correct Way to Make My Pyqt Application Quit When Killed from the Console (Ctrl-C)
Pandas: Update Column Values from Another Column If Criteria
How to Change the Foreground or Background Colour of a Tkinter Button on MAC Os X
Cv2 Image Error: Error: (-215:Assertion Failed) !Ssize.Empty() in Function 'Cv::Resize'
Python Anaconda - How to Safely Uninstall
Python3 Tkinter Set Image Size
How to Count the Number of Files in a Directory Using Python
Iterate Over Worksheets, Rows, Columns
How to Change a Dataframe Column from String Type to Double Type in Pyspark
How to Create an Automatically Updating Gui Using Tkinter
Counting the Number of Duplicates in a List
How to Test If a Column Exists and Is Not Null in a Dataframe
How to Convert Float into Hours Minutes Seconds
How to Use Anaconda Python to Execute a .Py File