使用自我访问类方法和变量 [英] Access Class method and variable using self

查看:83
本文介绍了使用自我访问类方法和变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In below example Test class has two instance method and one classmethod

set_cls_var_1 方法中,我设置了类

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

In set_cls_var_2 method I call class method using 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可以自己调用,为什么不能class变量

My question is: why only classmethod can call by self, Why not class variable

推荐答案

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

When you attempt to access an object's attribute using self, Python first searches the object's attributes. If it cannot find it there, then is searches the object's class's attributes. That is what's happening in your case;

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

Python first searches t's attributes. It doesn't find cls_var, so it then searches the T class's attributes. It finds cls_var so it stops, and returns cls_var's value.

但是,当将属性分配给 self 时,Python始终将其直接分配给对象,除非明确指示,否则永远不会将其分配给对象的类。这就是为什么将 self.cls_var 设置为 100 不会影响 Test cls_var 属性。

However, when assigning attributes to self, Python always assigns them directly to the object, and never the object's class unless explicitly told to do so. That's why assinging self.cls_var to 100 didn't affect Test's cls_var attrbiute.

这篇关于使用自我访问类方法和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆