问题描述
我是Python的初学者,刚开始接触类.我敢肯定这可能是非常基本的东西,但是为什么要这样写代码:
I'm a beginner at Python just getting to grips with classes. I'm sure it's probably something very basic, but why does this code:
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
编辑:我将代码更改为此:
EDIT: I changed the code to this:
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'
同样,这是从刚开始上课的人那里来的,所以如果我做了明显明显的错误,请不要太苛刻.谢谢.
Again, this is coming from someone just starting with classes, so please don't be too harsh if I've done something glaringly obvious wrong. Thank you.
推荐答案
您在 __ init __
中分配一个 channel
属性:
self.channel = 1
这遮盖了类上的 channel()
方法.重命名属性或方法.
This shadows the channel()
method on the class. Rename the attribute or the method.
属性胜过类上的属性(数据描述符除外;请考虑 property
s).从类定义文档:
Attributes on the instance trump those on the class (except for data descriptors; think property
s). From the Class definitions documentation:
您的方法还期望您在示例中未传递的参数,但我认为您接下来将自己解决该问题.
Your methods also expect a parameter that you are not passing in in your example, but I'm figuring you'll solve that yourself next.
这篇关于TypeError-Python中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!