为变量分配类

2024-04-25 08:33:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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")

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


Tags: nametestselfobjectinitdefdosp
1条回答
网友
1楼 · 发布于 2024-04-25 08:33:05

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的链接

相关问题 更多 >