Search code examples
pythonpython-3.xclasspython-class

How to change Class Variable from function in another Class


As you can see from below code i want to change Company class name variable from Owner class change_company_name function How can ı do that ? thanks

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)

Solution

  • your code is correct, you just have to call the method of the 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)
    

    out

    Another Company Name
    

    and if i comment the method call

    o = Owner()
    # o.change_company_name()
    
    print(Company.name)
    

    output

    I know that here is changing the Company name