【问题标题】:How to change Class Variable from function in another Class如何从另一个类中的函数更改类变量
【发布时间】:2021-05-30 20:51:42
【问题描述】:

正如您从下面的代码中看到的,我想从 Owner 类 change_company_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)

【问题讨论】:

    标签: python python-3.x class python-class


    【解决方案1】:

    你的代码是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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-11
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-19
      相关资源
      最近更新 更多