can a function in python behave like a class?

  • Last Update :
  • Techknowledgy :

You can consider a function to be an instance of a class that only implements __call__, i.e.

def foo(bar):
   return bar

is roughly equivalent to

class Foo(object):

   def __call__(self, bar):
   return bar

foo = Foo()

Adding an attribute to a function can be used, for example, to implement a memoization decorator, which caches previous calls to a function:

def memo(f):
def func( * args):
   if args not in func.cache: # access attribute
func.cache[args] = f( * args)
return func.cache[args]
func.cache = {}
# add attribute
return func

Note, however, that multiply, which was not made an attribute of foo, is not accessible from outside the function:

>>> foo.multiply(1, 2)

Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
      foo.multiply(1, 2)
      AttributeError: 'function' object has no attribute 'multiply'

The other question addresses exactly what you're trying to do:

>>> import inspect
>>> import new
>>> class AddOne(object):
"""Class definition."""

def __init__(self, num):
self.num = num

def getResult(self):
"""Class method."""
def addOneFunc(num):
"inner function"
return num + 1
return addOneFunc(self.num)

>>> two = AddOne(1)
>>> for c in two.getResult.func_code.co_consts:
if inspect.iscode(c):
print new.function(c, globals())

<function addOneFunc at 0x0321E930>

Not sure if the following is what you're thinking about, but you can do this:

>>> def f(x):
... print(x)
>>> f.a = 1
>>> f.a
>>> f(54)
>>> f.a = f
>>> f
<function f at 0x7fb03579b320>
   >>> f.a
   <function f at 0x7fb03579b320>
      >>> f.a(2)

If you want to access the local variables inside the function, I think then it's more difficult, and you may indeed need to revert to introspection. The example below uses the func_code attribute:

>>> def f(x):
   ...a = 1
   return x * a
   f.func_code.co_varnames('x', 'a') >>>
   f.func_code.co_consts(None, 1)

Suggestion : 2

Apr 16th, 2019 10:20 am | Comments , Posted by Trey Hunner Apr 16th, 2019 10:20 am python

>>> zip
<class 'zip'>
   >>> len
   <built-in function len>
      >>> int
      <class 'int'>
>>> reversed
<class 'reversed'>
   >>> enumerate
   <class 'enumerate'>
      >>> range
      <class 'range'>
         >>> filter
         <class 'filter'>
>>> something() >>>
   x = AnotherThing() >>>
   something_else(4, 8, * x)

Suggestion : 3

In Python, functions behave like any other object, such as an int or a list. That means that you can use functions as arguments to other functions, store functions as dictionary values, or return a function from another function. This leads to many powerful ways to use functions.,A function that uses another function as an input argument or returns a function (HOF) is known as a higher-order function. The most familiar examples are map and filter.,The operator module provides “function” versions of common Python operators (+, *, [] etc) that can be easily used where a function argument is expected.,The most useful function in the functools module is partial, which allows you to create a new function from an old one with some arguments “filled-in”.

import os
import sys
import glob
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
   matplotlib inline %
   precision 4
u '%.4f'
def square(x):
"Square of x."
return x * x

def cube(x):
"Cube of x."
return x * x * x
# create a dictionary of functions

funcs = {
   'square': square,
   'cube': cube,
x = 2

print square(x)
print cube(x)

for func in sorted(funcs):
   print func, funcs[func](x)
cube 8
square 4

Suggestion : 4

Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.,Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:,Class instantiation uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class. For example (assuming the above class):,The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named __init__(), like this:

def scope_test():
   def do_local():
   spam = "local spam"

def do_nonlocal():
   nonlocal spam
spam = "nonlocal spam"

def do_global():
   global spam
spam = "global spam"

spam = "test spam"
print("After local assignment:", spam)
print("After nonlocal assignment:", spam)
print("After global assignment:", spam)

print("In global scope:", spam)
After local assignment: test spam
After nonlocal assignment: nonlocal spam
After global assignment: nonlocal spam
In global scope: global spam
class ClassName:
class MyClass:
"A simple example class"
i = 12345

def f(self):
   return 'hello world'
x = MyClass()
def __init__(self): = []

Suggestion : 5

You don’t need to import the decorators: they’re automatically available to your step implementation modules as global variables.,The change is immediate and may be performed between step definitions in your step implementation modules - allowing adjacent steps to use different matchers if necessary.,Step functions are identified using step decorators. All step implementations should normally start with the import line:,The decorators all take a single string argument: the string to match against the feature file step text exactly. So the following step implementation code:

from behave
import *
@given('some known state')
def step_impl(context):
   set_up(some, state)
Scenario: test something
Given some known state
then some observed outcome.
Given some known state
and some other known state
when some action is taken
then some outcome is observed
but some other outcome is not observed.
@given('some other known state')
def step_impl(context):
   set_up(some, other, state)
from behave
import register_type, given
import parse

#--TYPE CONVERTER: For a simple, positive integer number.
@parse.with_pattern(r "\d+")
def parse_number(text):
   return int(text)

register_type(Number = parse_number)

#--STEP DEFINITIONS: Use type converter.
@given('{amount:Number} vehicles')
def step_impl(context, amount):
   assert isinstance(amount, int)

Suggestion : 6

By Bernd Klein. Last modified: 01 Feb 2022.

4 + 5
3.8 + 9
"Peter" + " " + "Pan"
'Peter Pan'

Suggestion : 7

Last Updated : 27 Feb, 2020

object() is shorthand
for object.__call__()

Output :

Instance Created
Instance is called via special method

Suggestion : 8

Many classes are inherited from other classes, but the one in the example is not. Many classes define methods, but this one does not. There is nothing that a Python class absolutely must have, other than a name. In particular, C++ programmers may find it odd that Python classes don't have explicit constructors and destructors. Although it's not required, Python classes can have something similar to a constructor: the __init__() method.,The name of this class is Student, and it doesn't inherit from any other class. Class names are usually capitalized, but this is only a convention, not a requirement. Everything in a class is indented, just like the code within a function, if statement, for loop, or any other block of code. The first line not indented is outside the class.,Unlike C++, classes in Python are objects in their own right, even without instances. They are just self-contained namespaces. Therefore, as long as we have a reference to a class, we can set or change its attributes anytime we want. ,The first parameter of __init()__ method, self, is equivalent to this of C++. Though we do not have to pass it since Python will do it for us, we must put self as the first parameter of nonstatic methods. But the self is always explicit in Python to make attribute access more obvious.

The following statement makes a class with no attributes attached, and in fact, it's an empty namespace object:

class Student:

In the code, the pass is the no-operation statement. This Student class doesn't define any methods or attributes, but syntactically, there needs to be something in the definition, thus the pass statement. This is a Python reserved word that just means move along, nothing to see here. It's a statement that does nothing, and it's a good placeholder when we're stubbing out functions or classes. The pass statement in Python is like an empty set of curly braces {} in Java or C.

>>> = "Jack" >>> = 20001

>>> print(

To instantiate a class, simply call the class as if it were a function, passing the arguments that the __init__() method requires. The return value will be the newly created object. In Python, there is no explicit new operator like there is in c++ or Java. So, we simply call a class as if it were a function to create a new instance of the class:

s = Student(args)

We can use the Student class defined above as following:

studentA = Student("Jack")
studentB = Student("Judy", 10005)