使用self访问类方法和变量

时间:2017-07-15 18:47:17

标签: python python-2.7 class class-method class-variables

在下面的示例中,测试类有两个实例方法和一个classmethod

set_cls_var_1 方法中,我使用self设置类变量。

set_cls_var_2 方法中,我使用self调用类方法。

   class Test():

        #class variable
        cls_var = 10

        def __init__(self):
           obj_var=20

        def set_cls_var_1(self,val):
            #second method to access class variable
            print "first "
            self.cls_var = val

        def set_cls_var_2(self):
            print "second"
            self.task(200)

        @classmethod
        def task(cls,val):
            cls.cls_var = val


t=Test()

#set class variable by first method
t.set_cls_var_1(100)

print Test.cls_var

#set class variable by second method
t.set_cls_var_2()

print Test.cls_var

输出

first 
10
second
200

预期输出

first 
100
second
200

我的问题是:    为什么只有classmethod可以自己调用,为什么不是类变量

3 个答案:

答案 0 :(得分:5)

当您尝试使用self访问对象的属性时,Python首先搜索对象的属性。如果在那里找不到它,则搜索对象的类的属性。这就是你的情况;

Python首先搜索t的属性。它找不到cls_var,因此它会搜索T类的属性。它会找到cls_var,因此会停止,并返回cls_var的值。

但是,在为self分配属性时,Python总是将它们直接分配给对象,而不是对象的类,除非明确告知它这样做。这就是为self.cls_var 100分配Test不会影响cls_var的{​​{1}} attrbiute。

答案 1 :(得分:1)

在定义Test类时,python创建一个名为Test的类对象,其属性cls_var等于10.当您实例化此类时,创建的对象没有cls_var属性。当调用self.cls_var时,由于python解析属性的方式,它实际上是检索的类'属性。

但是当设置self.cls_var时,该值设置在对象级别!因此,进一步调用self.cls_var将为您提供对象属性的值,而不再是类'!

也许这段代码会让这个更清晰:

class A(object):
    a = 1
a = A()
print a.a  # prints 1
A.a = 2
print a.a  # prints 2

您会看到,即使在类级别设置值时,也会对对象重新进行更改,因为,如果在对象级别找不到该属性,python将在该类中查找该属性。

调用Test.cls_var时,它是您正在访问的类的cls_var属性!不是您刚刚修改的对象之一。

答案 2 :(得分:1)

我发现其他一些总是使用以下方式来访问实例方法

中的classmethod或变量的东西
class Test():
    #class variable
    cls_var = 10

    def __init__(self):
        obj_var=20

    def set_cls_var_1(self,val):
        #first method to access class variable
        print "first type"
        cls = self.__class__
        cls.cls_var = val



t=Test()
#set class variable by first method

t.set_cls_var_1(100)

print Test.cls_var
相关问题