程序必须有两个类和两个对象,属于不同的阶层;一个对象使用其类的方法,必须处理另一个对象的数据。
示例:
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)