我是 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()
产生以下错误:
TypeError: 'int' object is not callable, Line 18
编辑:我将代码更改为:
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()
但它返回:
TypeError: change() missing 1 required positional argument: 'channel'
再次声明,这是来自刚开始类的人,所以如果我做错了一些明显的错误,请不要太苛刻。谢谢。
最佳答案
您在 __init__
中分配一个 channel
属性:
self.channel = 1
这会隐藏类中的 channel()
方法。重命名属性或方法。
实例的属性胜过类的属性(数据描述符除外;想想 property
)。来自Class definitions documentation :
Variables defined in the class definition are class attributes; they are shared by instances. Instance attributes can be set in a method with
self.name = value
. Both class and instance attributes are accessible through the notation “self.name
”, and an instance attribute hides a class attribute with the same name when accessed in this way.
您的方法还需要一个您未在示例中传递的参数,但我想您接下来会自己解决这个问题。
关于python - TypeError - Python 中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15668246/