TypeError - Python中的类

Laz*_*h13 4 python class typeerror

我是Python的初学者,只是掌握了课程.我敢肯定它可能是非常基本的,但为什么这个代码:

class Television():
    def __init__(self):
        print('Welcome your TV.')
        self.volume = 10
        self.channel = 1
    def channel(self, channel):
        self.channel = input('Pick a channel: ')
        print('You are on channel ' + self.channel)
    def volume_up(self, amount):
        self.amount = ('Increase the volume by: ')
        self.volume += self.amount
        print('The volume is now ' + self.volume)
    def volume_down(self, amount):
        self.amount = ('Decrease the volume by: ')
        self.volume -= self.amount
        print('The volume is now ' + self.volume)
myTele = Television()
myTele.channel()
myTele.volume_up()
myTele.volume_down()
Run Code Online (Sandbox Code Playgroud)

产生以下错误:

TypeError: 'int' object is not callable, Line 18
Run Code Online (Sandbox Code Playgroud)

编辑:我将代码更改为:

class Television():
    def __init__(self, volume = 10, channel = 1):
        print('Welcome your TV.')
        self.volume = volume
        self.channel = channel
    def change(self, channel):
        self.channel = input('Pick a channel: ')
        print('You are on channel ' + self.channel)
    def volume_up(self, amount):
        self.amount = int(input('Increase the volume by: '))
        self.volume += self.amount
        print('The volume is now ' + str(self.volume))
    def volume_down(self, amount):
        self.amount = int(input('Decrease the volume by: '))
        self.volume -= self.amount
        print('The volume is now ' + str(self.volume))
myTele = Television()
myTele.change()
myTele.volume_up()
myTele.volume_down()
Run Code Online (Sandbox Code Playgroud)

但它返回:

TypeError: change() missing 1 required positional argument: 'channel'
Run Code Online (Sandbox Code Playgroud)

再一次,这是来自刚开始上课的人,所以如果我做了一些明显错误的事情,请不要太苛刻.谢谢.

Mar*_*ers 7

您在以下位置指定了一个channel属性__init__:

self.channel = 1
Run Code Online (Sandbox Code Playgroud)

这会影响channel()类上的方法.重命名属性或方法.

实例上的属性胜过类上的属性(数据描述符除外;想想propertys).从类定义文档:

类定义中定义的变量是类属性; 它们由实例共享.可以在方法中设置实例属性self.name = value.类和实例属性都可以通过符号" self.name" 访问,并且实例属性在以这种方式访问​​时会隐藏具有相同名称的类属性.

你的方法也期望你的例子中没有传入的参数,但我想你接下来会解决这个问题.

  • Martijn,你有多好?我的意思是每次我打开一个Python问题你都是第一次尝试:) (3认同)