Home > Net >  Passing one variable from one class to another
Passing one variable from one class to another

Time:07-20

i am take the no. of iteration in for loop running from a different class.

for e in range(1,EPOCHS 1 ):
g=0 
for j in range (jin):
   g=g 1
   print(g)
   train_epoch_loss = 0
   train_epoch_acc = 0   

   p1=cross(g)
   #pw=pq.save(g)
   #p1=pq.get()
   model.train()

and saving it in this class and need to use that value.

class cross():  
c=0
def init__ (self,value):
    self.v = value
    print('i entered the classs')

for train_index, test_index in kf.split(x_trainval):
    c=c 1
  #      e1=num()
    x_train,x_val=x[train_index],x[test_index]
    y_train,y_val=y[train_index],y[test_index]
    print("TRAIN:", train_index, "TEST:", test_index)
    print("epoch",c)
            #     print(e1.__getitem__())
    if (v == c):
        print("compare")
        break

train_dataset = classifierdataset(torch.from_numpy(x_train).float(), torch.from_numpy(y_train).long())
val_dataset = classifierdataset(torch.from_numpy(x_val).float(), torch.from_numpy(y_val).long()) 
test_dataset = classifierdataset(torch.from_numpy(x_test).float(), torch.from_numpy(y_test).long())   


train_loader = DataLoader(dataset=train_dataset, batch_size=BATCH_SIZE)

val_loader = DataLoader(dataset = val_dataset, batch_size = 1)

test_loader = DataLoader(dataset = test_dataset , batch_size = 1)
print("train",x_train,"val",x_val)

Now the issues i am having is how to use the set value in the same class.

CodePudding user response:

just put a return statement and take the values accordingly to the return statement.

CodePudding user response:

I think you are asking if you can access obj.value within other methods or self.value within the same class methods .

Maybe this will help you ,

https://medium.com/python-features/class-vs-instance-variables-8d452e9abcbd#:~:text=Class variables are shared across,surprising behaviour in our code.

Accessing an instance variable within an instance method (a method that accepts self as first argument) - Correct way -

class Student:
    # constructor
    def __init__(self, name, age):
        # Instance variable
        self.name = name
        self.age = age

    def show(self):
        print('Name:', self.name, 'Age:', self.age)

Wrong way -

class Student:
    # constructor
    def __init__(self, name, age):
        # Instance variable
        self.name = name
        self.age = age

    # instance method access instance variable
    def show(self):
        print('Name:', name, 'Age:', age)

student_obj.show()

gives

NameError: name 'name' is not defined

within some other method you need to have the obj available :

c_obj = cross(5)

def any_other_method(c: cross) -> None:
    print("value is ", c.v)

any_other_method(c_obj) prints "value is 5"
  • Related