Home > OS >  OOP - Use a method of one object to process the data of another object from a different class
OOP - Use a method of one object to process the data of another object from a different class

Time:11-26

The program must have two classes and two objects, belonging to different classes; one object, using a method of its class, must process the data of another object.

example:

obj1.method(obj2.property)

Here is my code :

class first:
    name="first"


class second:
    def change_first(self):
        name="not first"


obj1 = first()
obj2 = second()
    
print(obj1.name)

But obj2 is not changing obj1 name.

CodePudding user response:

Assuming I understand what you mean:

class First:
    #use init to run at initialisation
    def __init__(self):
        #use self to assign this variable to the object
        self.name = "first"

class Second:
    def change_name(self):
        obj1.name = "not_first"

obj1 = First()
obj2 = Second()
print(obj1.name)
#change name
obj2.change_name()
print(obj1.name)
  • Related