python - Python 类,没有得到预期的返回值,与内部方法混淆
问题描述
我正在学习 python,我在类 Onject 上苦苦挣扎,我有以下类:
class Delivery(object):
def __init__(self, recipient, nn, cost, weight):
self.name = recipient
self.value = nn
self.cost = cost
self.weight = weight
def get_recipient(self):
return self.name
def get_priority_category(self):
if self.get_priority_value >= 8:
return "Urgent"
elif self.get_priority_value >= 5 and self.get_priority_value <= 7:
return "High"
elif self.get_priority_value >= 3 and self.get_priority_value <= 4:
return "Medium"
elif self.get_priority_value < 3:
return "Low"
def get_priority_value(self):
return self.nn
def get_cost(self):
return self.cost
def get_weight(self):
return self.weight
def get_cw_ratio(self):
ratio = self.cost / self.weight
return str(round(ratio, 2))
def __str__(self):
return '<' + self.get_recipient + ', ' + str(self.get_priority_category)+ ', ' + str(self.get_cost)+ ', ' + str(self.get_weight) + '>'
我期望发生的是这样的:
PackageOne = Delivery('John', 1, 2, 4)
print(PackageOne)
结果应该是<John, Low, 2, 4>
我怎么得到以下
<John, <bound method Delivery.get_priority_category of <__main__.Delivery object at 0x110866860>>, <bound method Delivery.get_cost of <__main__.Delivery object at 0x110866860>>, <bound method Delivery.get_weight of <__main__.Delivery object at 0x110866860>>>
我觉得我没有在方法上使用正确的回报?
解决方案
你没有调用你的方法。您将看到方法对象本身的表示,而不是它们的结果。
添加()
调用:
def __str__(self):
return (
'<' + self.get_recipient() + ', ' +
self.get_priority_category() + ', ' +
str(self.get_cost()) + ', ' +
str(self.get_weight()) +
'>')
我放弃了多余的str()
调用(get_recipient()
并且get_priority_category()
已经在生成字符串),并(...)
在表达式周围添加,以便可以将其拆分为多行以提高可读性。
并不是说您需要大多数这些方法,因为您可以直接访问底层属性:
def __str__(self):
return (
'<' + self.name + ', ' +
self.get_priority_category() + ', ' +
str(self.cost) + ', ' +
str(self.weight) +
'>')
在 Python 中,您通常不使用访问器函数,而不是直接访问属性就足够了。这与 Java 等语言不同,后者在事后很难用访问器函数替换属性访问。在 Python 中,稍后切换到使用属性是微不足道的property
,因此直接使用属性没有成本。
以上可以通过使用字符串格式化来简化;对于 Python 3.6 及更高版本,使用 f 字符串:
def __str__(self):
return f'<{self.name}, {self.get_priority_category()}, {self.cost}, {self.weight}>'
否则使用str.format()
做同样的事情:
def __str__(self):
return '<{}, {}, {}, {}>'.format(
self.name, self.get_priority_category(), self.cost, self.weight)
使用字符串格式时,无需str()
调用,您可以节省大量输入'
和+
字符。
推荐阅读
- version-control - 在项目的版本控制中存储 supervisord 配置?
- mysql - 如何将 JSON 数据添加或合并到现有 MySQL 行的 JSON 字段中?
- ios - 成为第一响应者时,标题视图中的搜索栏不再居中
- augmented-reality - 如何在 ar.js 中不使用任何标记插入对象
- html - 启用严格的 MIME 检查错误
- swift - Swift 除法“/”运算符不工作还是我错过了什么?
- javascript - 将一串字符串拆分为 2 个分隔符
- indy - Delphi 和 Walmart 批量 API 上传 - 内部服务器错误
- android - 启动画面后如何停止黑屏?
- angular - Angular 4:ngFor内部html不起作用