问题描述
正如您从下面的代码中看到的,我想从 Owner 类 change_company_name 函数中更改 Company 类名称变量 我怎样才能做到这一点 ? 谢谢
class Company:
name = "A Company name"
def __init__(self,num_of_employees,found_year):
self.num_of_employees = num_of_employees
self.found_year = found_year
class Owner:
Company.name = "I kNow that here is changing the Company name"
def change_company_name(self): ### I want to change Company name from function in another Class
Company.name = "Another Company Name"
print(Company.name)
解决方法
你的代码是correct
,你只需要call
类的方法。
class Company:
name = "A Company name"
def __init__(self):
# i removed the params to
# make a simple example
pass
class Owner:
# its working
Company.name = "I know that here is changing the Company name"
def change_company_name(self):
# and its working
Company.name = "Another Company Name"
# create an object of the class
# in order the change through the function
o = Owner()
o.change_company_name()
print(Company.name)
出
Another Company Name
如果我评论 method call
o = Owner()
# o.change_company_name()
print(Company.name)
输出
I know that here is changing the Company name