Python OOP – 对象没有属性
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Python OOP – 对象没有属性,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1931字,纯文字阅读大概需要3分钟。
内容图文
![Python OOP – 对象没有属性](/upload/InfoBanner/zyjiaocheng/800/de899c2fc8bd469394ddcd60ad035576.jpg)
我正在尝试学习如何编程.我真的很想学习如何编程;我喜欢它的建筑和设计方面.但是,在Java和Python中,我已经尝试过失败的程序,因为它们与对象,类,方法有关.我正在尝试为程序开发一些代码,但我很难过.我知道这是一个简单的错误.但是我输了!我希望有人可以指导我参加一个工作计划,但也帮助我学习(批评不仅是预期,而且是受到赞赏的).
class Converter:
def cTOf(self, numFrom):
numFrom = self.numFrom
numTo = (self.numFrom * (9/5)) + 32
print (str(numTo) + ' degrees Farenheit')
return numTo
def fTOc(self, numFrom):
numFrom = self.numFrom
numTo = ((numFrom - 32) * (5/9))
return numTo
convert = Converter()
numFrom = (float(input('Enter a number to convert.. ')))
unitFrom = input('What unit would you like to convert from.. ')
unitTo = input('What unit would you like to convert to.. ')
if unitFrom == ('celcius'):
convert.cTOf(numFrom)
print(numTo)
input('Please hit enter..')
if unitFrom == ('farenheit'):
convert.fTOc(numFrom)
print(numTo)
input('Please hit enter..')
解决方法:
类和对象是完成任务的工具 – 它们允许您使用一组方法封装数据或状态.但是,您的数据只是一个数字.无需封装整数,因此无需创建类.
换句话说,不要创建一个类,因为你认为应该创建一个类,因为它使你的代码更简单.
import sys
def f_to_c(x):
return (x - 32) * (5/9)
def c_to_f(x):
return x * (9/5) + 32
num_from = float(input('Enter a number to convert: '))
unit_from = input('What units would you like to convert from? ')
unit_to = input('What units would you like to convert to? ')
if (unit_from, unit_to) == ('fahrenheit', 'celsius'):
num_to = f_to_c(num_from)
elif (unit_from, unit_to) == ('celsius', 'fahrenheit'):
num_to = c_to_f(num_from)
else:
print('unsupported units')
sys.exit(1)
print('{} degrees {} is {} degrees {}'
.format(num_from, unit_from, num_to, unit_to))
Enter a number to convert: 40 What units would you like to convert from? celsius What units would you like to convert to? fahrenheit 40.0 degrees celsius is 104.0 degrees fahrenheit
转换对象和Converter类不起任何作用,因此代码更简单,更容易阅读.
内容总结
以上是互联网集市为您收集整理的Python OOP – 对象没有属性全部内容,希望文章能够帮你解决Python OOP – 对象没有属性所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。