【问题标题】:can anyone please explain me this piece of code谁能解释一下这段代码
【发布时间】:2019-08-07 10:45:30
【问题描述】:

我知道这是一个菜鸟问题,但我正在学习 OOP,无法计算得到的输出

这是我找到的代码,我可以知道它是如何运行的吗?

class InstanceCounter(object):
    count = 0

    def __init__(self, val):
        self.val = val
        InstanceCounter.count += 1

    def set_val(self, newval):
        self.val = newval

    def get_val(self):
        print(self.val)

    def get_count(self):
        print(InstanceCounter.count)

a = InstanceCounter(5)
b = InstanceCounter(10)
c = InstanceCounter(15)

for obj in (a, b, c):
    print("value of obj: %s" % obj.get_val())
    print("Count : %s" % obj.get_count())

【问题讨论】:

  • 我猜你得到的输出是 5, 3, 10, 3, 15, 3 ?
  • 是的,它是正确的,但我可以知道我们是如何得到的吗
  • 我可以知道为什么我们在 5 之后得到 3 吗?

标签: python-3.x


【解决方案1】:

您有一个名为InstanceCounter 的类,它继承自object。如果您使用Python3,则object 的继承可以是removed。这个类有一个属性countvalue和一些methods(函数——例如set_val)。

现在,您创建类的三个对象并将value 的值设置为51015,方法是将这些值传递给构造函数。您还可以在每次构造函数调用时将 static 属性(参见 herecount 增加一。静态属性与符号 Class.Attribute 一起使用。

在最后一步中,循环遍历三个对象的列表 ((a, b, c)) 并将每个对象存储在对象 obj 中,因此 obj 将代表 a 然后 b 然后 @ 987654343@。所以你可以调用这个对象的方法,因为你的对象obj的类型是InstanceCounter,所以obj包含相同的方法和属性。

顺便说一句,我重新编写了您的代码,使其更易于理解并使用Python3 语法。

class InstanceCounter:
    count = 0

    def __init__(self, val):
        self.val = val
        InstanceCounter.count += 1

    def set_val(self, newval):
        self.val = newval

    def get_val(self):
        return self.val

    def get_count(self):
        return InstanceCounter.count

a = InstanceCounter(5)
print("Count : {}".format(a.get_count()))
b = InstanceCounter(10)
print("Count : {}".format(b.get_count()))
c = InstanceCounter(15)
print("Count : {}".format(c.get_count()))

for obj in (a, b, c):
    print("value of obj: {}".format(obj.get_val()))
    print("Count : {}".format(obj.get_count()))

这导致以下输出:

Count : 1
Count : 2
Count : 3
value of obj: 5
Count : 3
value of obj: 10
Count : 3
value of obj: 15
Count : 3

为了更好地理解静态属性:

因此,如果您有三个类型为 InstanceCounter 的对象,则您有 三个不同的 名称为 val 的属性,因为每个类型为 InstanceCounter 的对象都包含一个属性 val - 一个 instance attribute一个相同的属性,名称为count - 一个class attribute

  • count 是类 InstanceCounterclass attribute。这 属性对于所有具有类型的对象具有相同的值 InstanceCounter。与 Classname.Attributename 一起使用 - 例如 InstanceCounter.count
  • valinstance attribute,因为 InstanceCounter 类的每个 instance 都有自己的值。与 Instancename.Attributename 一起使用 - 例如 a.val

更多信息请参见here

【讨论】:

  • 我明白了一点,但我对 obj 5 的值有一个愚蠢的怀疑,为什么计数是 3 并且所有值都相同?
  • 我们有 3 个对象,所以 obj.get_count() 是 3??
  • 我更新了我的文字以澄清这个问题。希望它现在对您有所帮助。
猜你喜欢
  • 2017-04-22
  • 1970-01-01
  • 2021-04-24
  • 2014-09-16
  • 1970-01-01
  • 2011-02-11
相关资源
最近更新 更多