嗨,我需要一个帮助,我的简单编程是与名称

2024-09-30 08:32:26 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我需要帮助我的简单编程是NameError,我的代码:

class Televisao():
    def __init__(self,boolean, channel):
        self.channel = 2
        self.boolean = False
    def main():
       tvhome =Televisao()
    print tvhome.channel

    if __name__== "__main__" :
        main()

NameError: name 'tvhome' is not defined


Tags: 代码nameselffalseinitmaindef编程
2条回答
class Televisao():
    def __init__(self,boolean, channel):
         self.channel = 2
         self.boolean = False

if __name__== "__main__" :
    tvhome = Televisao()
    print tvhome.channel

更新: 似乎您已经在函数内部创建了实例,并从外部调用了它。你知道吗

 def main():
     tvhome = Televisao() # now tvhome is local variable.

 print tvhome.channel  # you will get the error : undefined 

更新: 另一个错误将会发生,正如你所说

tvhome = Televisao() # without its __init__ parameters boolean , channel
class Televisao:
    def __init__(self, is_on, channel):
        self.is_on = is_on
        self.channel = channel

def main():
   tvhome = Televisao(True, 13)
   print(tvhome.channel)

if __name__== "__main__":
    main()

相关问题 更多 >

    热门问题