OOP - 使用一个对象的方法来处理来自不同 class 的另一个对象的数据

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

程序必须有两个 classes 和两个对象, 属于不同的 classes;一个对象使用其 class 的方法必须处理另一个对象的数据。

示例:

obj1.method(obj2.property)

这是我的代码:

class first:
    name="first"


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


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

但 obj2 并未更改 obj1 名称。

假设我明白你的意思:

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)