TypeError – Python中的类
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了TypeError – Python中的类,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2109字,纯文字阅读大概需要4分钟。
内容图文
![TypeError – Python中的类](/upload/InfoBanner/zyjiaocheng/803/2fbb20d28aa2478d8ae964d6ed74cbf3.jpg)
我是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__中指定了一个频道属性:
self.channel = 1
这会影响类上的channel()方法.重命名属性或方法.
实例上的属性胜过类上的属性(数据描述符除外;想想属性).从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.
你的方法也期望你的例子中没有传入的参数,但我想你接下来会解决这个问题.
内容总结
以上是互联网集市为您收集整理的TypeError – Python中的类全部内容,希望文章能够帮你解决TypeError – Python中的类所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。