How to Assign Class Instance to a Variable and Use That in Other Class

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:

  1. 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";

  1. 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



Leave a reply



Submit