【问题标题】:Python changing class variablesPython更改类变量
【发布时间】:2013-03-25 07:18:42
【问题描述】:

好的,这次我会尽量说清楚。

class Yes:

    def __init__(self):
        self.a=1

    def yes(self):
        if self.a==1:
            print "Yes"
        else:
            print "No, but yes"

class No(Yes):

    def no(self):
        if self.a==1:
            print "No"
        else:
            print "Yes, but no"
        self.a-=1 #Note this line

现在,在运行时:

Yes().yes()
No().no()
Yes().yes()
No().no()

我希望它打印出来:

Yes
No
No, but yes
Yes, but no

它给了我:

Yes
No
Yes
No

现在,我知道原因是因为我只是在 No 类中更改 Self.a 的值(还记得那行吗?)。我想知道是否有任何方法可以在 Yes 类中更改它,而仍在 No 类中(例如,如果我可以插入一些东西来代替 self.a-=1 可以工作)。

【问题讨论】:

  • 可以在类中写一个setter方法,从其他类调用
  • 我试过了,一直回调self.a=1
  • @MichalČihař 特别是this answer 触及了问题的核心:您不能通过self 设置类变量。您必须改用类名。混乱来自能够通过self获取一个类变量。

标签: python class variables


【解决方案1】:

我不确定您对此有什么可能的用途,但是...

您想操作 class 变量,但您一直在处理实例变量。如果要类变量,请使用类变量!

class Yes:
    a = 1 # initialize class var.
    def __init__(self):
        self.a = 1 # point of this is what?

    def yes(self):
        if Yes.a==1: # check class var
            print "Yes"
        else:
            print "No, but yes"

class No(Yes):

    def no(self):
        if Yes.a==1: # check class var
            print "No"
        else:
            print "Yes, but no"
        Yes.a-=1 # alter class var

【讨论】:

  • 我用它作为我想做的其他事情的例子,谢谢
  • 使用这样的类变量看起来像是代码异味。你确定你正在做的事情不能以其他方式完成吗?
  • @FrancisAvila 我认为你被他在构造函数中的设置a 吓跑了。他只是试图演示一种改变类变量值的方法。答案是Yes.a = 1Moral of the story,可以通过self获取一个类变量,但是不能这样设置。
  • @BobStein 感谢您指出这一区别。仍然困扰着我!
  • @SujayPhadke 这对我来说也是一个反复出现的创伤。长期存在的 Python 陷阱:试图通过 self 设置类属性
【解决方案2】:

看来您要使用的是静态变量而不是实例变量。一个静态变量在类的所有实例之间共享。

class Yes:
    a = 1
    def __init__(self):
        pass

    def yes(self):
        if Yes.a==1:
            print "Yes"
        else:
            print "No, but yes"

class No(Yes):

    def no(self):
        if Yes.a==1:
            print "No"
        else:
            print "Yes, but no"
        Yes.a-=1 #Note this line

Yes().yes()
No().no()
Yes().yes()
No().no()

将输出:

Yes
No
No, but yes
Yes, but no

【讨论】:

  • 这不是一个静态变量,它是一个类变量。如果它改变了,它会随着班级而改变。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多