如何从另一个类中的函数更改类变量

问题描述

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...