Skip to main content
 首页 » 编程设计

python之将类分配给变量

2025年05月04日44tuyile006

class SimpleTestCase(object): 
 
    def __init__(self, name): 
        self.name = name 
        self.SP = SP 
 
    def __somemethod(self): 
     # do something 
 
class Test(object): 
    def __init__(self, name ): 
        self.name = name 
        self.case = SimpleWidgetTestCase 

有什么理由可以做

self.case = SimpleTestCase 

代替

simple_obj = SimpleTestCase("name") 

通过创建对象,可以访问类方法和变量。前者等同于后者吗?

请您参考如下方法:

Is there any reason to do
self.case = SimpleTestCase

是的,这是有原因的。有时人们希望在不创建实例的情况下存储类型。 创建一个实例可能代价高昂,例如,如果 __init__ 执行打开数据库连接、读取大文件等操作。

By creating object one can access the class methods and variables. Is the former equivalent to latter?

不,前者不等于后者。 在前者中,您将类型分配给变量。在后者中,您分配一个实例。
Python 允许您访问方法和变量,如果它们是类方法(或静态方法)或类变量。这样你就不需要创建和实例。 通过创建实例,您可以访问实例方法。

请参阅有关 difference between staticmethod and classmethod in python 的链接