【问题标题】:Is it possible to create a method by an argument是否可以通过参数创建方法
【发布时间】:2016-11-18 03:29:47
【问题描述】:

假设我有两个函数

def do1(x, y):
    return x + y

def do2(x, y):
    return x - y

我可以创建这样的类

class foo(object):
    def __init__(self, func):
        self.func = func

abc = foo(func=do1)
abc.func(1, 1)  # return 2
abc = foo(func=do2)
abc.func(1, 1)  # return 0

我可以让abc.func 成为方法而不是属性吗?

谢谢。

【问题讨论】:

  • 你的问题并不完全清楚,但也许stackoverflow.com/a/30294947 是你所追求的?
  • 去谷歌“Python 实例方法”。
  • abc.func 是方法,不是属性,因为你可以称它为abc.func()

标签: python class python-3.x object


【解决方案1】:

你可以像这样向一个类添加一个方法:

def do(self, x, y):
  return x+y

class Foo(object0:
  def __init(self):
    pass

Foo.bar = do

a = Foo()
a.bar(1,2)
out> 3

或者到一个实例:

def do2(x,y):
  return x + y

a = Foo()
a.bar2 = do2
a.bar2(3,4)
out> 7

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-12
    • 2011-06-13
    • 2012-10-13
    • 2021-01-14
    • 2021-07-20
    • 2016-10-13
    相关资源
    最近更新 更多