如何从另一个 Class 中的函数更改 Class 变量
How to change Class Variable from function in another Class
正如您从下面的代码中看到的,我想从 Owner class change_company_name 函数更改 Company class name 变量
我怎样才能做到这一点 ?
谢谢
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的方法。
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
正如您从下面的代码中看到的,我想从 Owner class change_company_name 函数更改 Company class name 变量 我怎样才能做到这一点 ? 谢谢
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的方法。
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