【问题标题】:Python add custom function to datatypesPython向数据类型添加自定义函数
【发布时间】:2023-03-27 07:39:01
【问题描述】:

我想添加一个可以直接从整数调用的函数或类,例如:

1.customFunction(parameters)
36.customFunctionTwo(onearg, twoarg)

我该怎么做?

【问题讨论】:

  • 正如这个 stackoverflow post 中所解释的,您需要按照 post 中的解释来继承 Integer 类。

标签: python class oop types


【解决方案1】:

Python 不会让您重新定义 int 类型,但使用字典可以做到:

class One:
  def __init__(self):
    pass
  def Custom(self,parameter1,parameter2):
    print(parameter1,parameter2)

dic={1:One()}

dic[1].Custom("Parameter 1","Parameter 2")

然后你只需对每个数字再做一次。

【讨论】:

    猜你喜欢
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    相关资源
    最近更新 更多