python - 类(class)/ self 问题

标签 python self

这是我的代码:

class Pop(object):
    def holder(self):
        self.boobs = 16
        self.sent = "pop"
    def together(self):
        print "%s : %i" % (self.sent, self.boobs)

pop = Pop()

pop.together()

这不应该打印“pop : 16”吗?抱歉奇怪的变量名 :P

另外,我是新手。谢谢。

最佳答案

在您的示例中,您应该首先调用 holder,因为这会将变量设置为 16。 我想你是想这样做:

class Pop(object):
    def __init__(self):
        self.boobs = 16
        self.sent = "pop"
    def together(self):
        print "%s : %i" % (self.sent, self.boobs)

pop = Pop()

pop.together()

关于python - 类(class)/ self 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6706715/

相关文章:

python - "TypeError: ' 将字节写入文件时列出' does not support the buffer interface"

python - 在 Python 中打印变量的 Unpythonic 方式?

python - 如何链接到 intersphinx 中的根页面

rust - self 的多个部分怎么能在这里借用?这里的 self borrowed mutably 和 immutably 不是一样的吗?

delphi - 分配 self 的后果

iphone - 什么时候用 self 访问属性,什么时候不访问?

python - 如何标准化直方图,使高度之和等于 1?

ios: self 在 block 中变为零?

function - 快速函数调用 : self-keyword vs without

python - 按行组合 Pandas 数据帧的有效方法