python - Is it possible to rewrite the outcome of 2*func(x) to be func(x) + func(x) in Python?
问题描述
This problem has been intriguing, even though it's not necessarily neat. I have the following code:
import random
def d(m):
return random.randint(1, m)
print(3*d(6))
This will print the returned value of d(6) and multiply that by 3. What I would like to have is to define a set of symbols so I can set that 3*d(6) will instead return: d(6) + d(6) + d(6). Alternatively is it possible to set the expression '3d6' to return what I want in a general case for XdY?
Is this solvable with wrappers / addition of symbols or do I have to go deeper and change stuff in the interpreter?
I'm trying to make the program read more naturally for the gaming genre. In tabletop gaming, people say "2d6", which means 'throw two 6-sided dice'. This has a different probability density function compared to 2*d(6).
解决方案
您不能产生int3*d(6)
的效果d(6)+d(6)+d(6)
并d(6)
返回 int。如果您正在创建表示概率分布或类似内容的对象,您可以__rmul__
按照您想要的方式重载,但不能使用整数。
你也不能3d6
评估你想要的。3d6
不是有效的 Python 令牌。您将不得不更改并重新编译 Python 源代码以生成您自己的具有更改语法的 Python 变体,这将是很多工作而没有什么好处。
推荐阅读
- php - PHP 使用多字符分隔符解析 csv
- c - struct 中指针的 malloc() 不会将内存绑定到声明的大小
- python - 如何将引导样式添加到我的 django 表单中?
- karma-jasmine - 为什么业力什么都不显示?
- java - 如何在运行时为当前测试 ApplicationContext 注册 Spring Context Events
- java - Java - 在函数调用中包含数组声明?
- android - 从活动中的项目单击回调函数更改回收站视图项目的颜色
- python - Python dateutil 返回 YYYY-MM-DD,但我需要它反转,请帮忙?
- javascript - 使用用户输入值而不是参数
- python - 如何在 Python 中将 Dictionary 转换为 QuerySet