Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
73 views
in Technique[技术] by (71.8m points)

python - What is the difference between a higher-order function and a class?

I was going through the basics of functional programming, and eventually came accross the concept of higher-order functions. I saw an example in this video by Corey Schafer (starts at 11:00), which shows a Python function that can wrap messages in arbitrary HTML tags:

def html_tag(tag):
    def wrap_text(msg):
        print('<{0}>{1}</{0}>'.format(tag, msg))

    return wrap_text

print_h1 = html_tag('h1')
print_h1('Test Headline!')
print_h1('Another Headline!')

print_p = html_tag('p')
print_p('Test Paragraph!')

Output:

<h1>Test Headline!</h1>
<h1>Another Headline!</h1>
<p>Test Paragraph!</p>

I get that it gives you the flexibility of re-using the same function for different purposes (different tags, in this example). But you could achieve the same result using Python classes, too:

class HTML_tag:
    def __init__(self, tag):
        self.tag = tag
    
    def wrap_text(self, msg):
        print('<{0}>{1}</{0}>'.format(self.tag, msg))

print_h1 = HTML_tag('h1')
print_h1.wrap_text('Test Headline!')
print_h1.wrap_text('Another Headline!')

print_p = HTML_tag('p')
print_p.wrap_text('Test Paragraph!')

Output:

<h1>Test Headline!</h1>
<h1>Another Headline!</h1>
<p>Test Paragraph!</p>

The higher-order function approach definitely looks cleaner, but apart from the aesthetics, are there any other reasons I might want to prefer a higher-order function over a class? E.g., regarding aspects like

  • Performance
  • Memory
  • ...
question from:https://stackoverflow.com/questions/65891682/what-is-the-difference-between-a-higher-order-function-and-a-class

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Higher order functions take and/or return functions. Let's look at both cases.

Taking a function as a parameter

Here, a HOF is definitely the way to go. The class version amounts to a HOF with extra steps. For the class version, you need to have pre-negotiated the key the function is callable on. It's really a useless wrapper around the meat of what you're trying to accomplish.

HOF

def my_map(fn, arr):
  result = []
  for a in arr:
    result.append(fn(a))
  return result

my_map(lambda a: a + 1, [1, 2, 3]) # [2, 3, 4]

Class version

def my_map(inst, arr):
  result = []
  for a in arr:
    result.append(inst.fn(a))
  return result

class my_mapper:
  def fn(self, a):
    return a + 1

my_map(my_mapper(), [1, 2, 3]) # [2, 3, 4]

Returning a function

In both versions here, what we're doing is creating an encapsulation of some value a, and a function that works over it.

I think that a class is generally useful if you want more than one function to be defined over some data, when the encapsulated data can change (you're encoding a state machine), or when you expect operations to be specific to your class (ie. users of your class need to know the operations defined over the class).

I would use a function that returns a function, when what I'm doing amounts to partial application, (I have a function that takes multiple parameters, and I want to preapply some, like 'add'). I would also use functools.partial to do this.

def adder(a):
  return lambda b: a + b
class adder_class:
  def __init__(self, a):
    self.a = a

  def add(self, b):
    return a + b

Ultimately, whether it's best to use a HOF or a class will become clear from context.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...