Skip to main content
 首页 » 编程设计

python之类(class)/ self 问题

2025年05月04日13lovecherry

这是我的代码:

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()