Since these are member functions, call it as a member function on the instance, self.

def isNear(self, p):
    self.distToPoint(p)
    ...
Answer from Jeff Mercado on Stack Overflow
Top answer
1 of 3
2

In this case, I think using different classes is probably the way to go.

from abc import ABC, abstractmethod

class Returns(ABC):
    def __init__(self, stock_ticker):
        self.stock_ticker = stock_ticker
    def get_price_data_from_ticker(self):
        pass # FIXME: implement getting stuff from the data source here
    @abstractmethod
    def calculate_returns(self, prices):
        pass
    def get_returns(self):
        return self.calculate_returns(self.get_price_data_from_ticker())

class ArithmeticReturns(Returns):
    def calculate_returns(self, prices):
        return [prices(i) - prices(i - 1) for i in prices]

class LogarithmicReturns(Returns):
    def calculate_returns(self, prices):
        return [np.ln(prices(i) / prices(i - 1)) for i in prices]

x = LogarithmicReturns('AAPL US Equity')
print(x.get_returns())

Concepts used:

  • Abstract Base Classes: Returns is now a class that cannot be substantiated, only subclasses that implement all abstract methods can. This means both subclasses implement the same interface without having to do all of the heavy lifting themselves.
  • List comprehensions: l = [a + 1 for a in exp] is equivalent to

    l = []
    for a in exp:
        l.append(a + 1)
    
  • Separation of concerns: calculate_returns is now no longer concerned with how data is collected from the ticker, it purely calculates the returns based on the prices given to it.

Your code contained syntax errors in arithmetic and logarithmic in the loops, so you will need to fix that. If prices is a list, I would use something like [current_price - previous_price for current_price, previous_price in zip(prices[1:], prices)], but I decided to leave it as is in case prices is actually a strange iterable that iterates over the indexes and is indexed by calling.

2 of 3
1

I think you're on the right way; but using some dependency injection might work better in your case. You could do something like this:

def arithmetic(prices):
    daily_ret = []
    for i rows in prices:
        returns.append(prices(i)-prices(i-1))
    return daily_ret

def logarithmic(prices):
    daily_ret = []
    for i rows in prices:
        returns.append(np.ln(prices(i) / prices(i-1))
    return daily_ret

class Returns:
    def __init__(self, stock_ticker, return_calc=arithmetic):
        self.stock_ticker = stock_ticker
        self.return_calc = return_calc

    def calculate_returns(self):
        get_price_data_from_ticker = whatever_data_source()
        return self.return_calc(get_price_data_from_ticker)

x = Returns('AAPL US Equity', return_calc=logarithmic)
print(x.calculate_returns())

by directly passing the function instead of passing a string constant to identify which function to use.

By the way, this is what you were doing in this line:

def __init__(self, stock_ticker, return_calc=arithmetic):

which means that the default value that you are passing right now isn't a string, but directly the function

Discussions

python - How can I call a function inside a class? - Stack Overflow
You said this is not how it must be. I would be grateful if you could tell me the reason. I'm at the very first stage of learning python. ... Save this answer. ... Show activity on this post. When calling member functions you have to use the self argument, and initiate the class. More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Call function from one class in the same class - Data Science Stack Exchange
I have 2 classes model and impute. I am defining a function mode_impute inside impute. Now I want to call mode_impute inside impute. How can I call it? I tried the following: class impute(model): ... More on datascience.stackexchange.com
๐ŸŒ datascience.stackexchange.com
December 5, 2021
python - How to call a function from an object within a class? - Stack Overflow
Incase what I am trying to accomplish ... level class that calls foo. Then passing an object with the functions already mapped. If someone could shed light on this alternative incase my desired end state is not possible. ... Forgot to add the handler call inside the ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to call function defined inside a class? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives ยท Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how do i call a function from within another function in a class?
r/learnpython on Reddit: How do I call a function from within another function in a class?
February 6, 2023 -

I'm learning to work with classes and I'm trying to turn my procedural code that's working perfectly into a class with a series of functions (def) within. I ran into an error while testing though. It says "name def2 is not defined," and I'm not sure how to define it.

I wrote:

from <file> import Class
x = Class()
x.def1()
x.df

So far it works perfectly and the data table looks like what I expect. def1 only uses self as a parameter.


After def1, def2-4 all use different parameters, so I can't simply write x.def2 like I did above, otherwise it errors out because I didn't input a second parameter.

Then def5 is another function with only self as a parameter that is merely a series of procedural lines that call upon def2-4 written above. However, when I tried to run x.def5(), it errors out saying "def2 is not defined," and if I comment out the def2 part, it errors out saying "def3 is not defined" instead.

How do I define these functions so I can call upon them in a separate function within the same class?

๐ŸŒ
Codearmo
codearmo.com โ€บ python-tutorial โ€บ object-orientated-programming-functions
Adding Functions to Python Classes | Codearmo
March 28, 2025 - Classes can be created as simply a collection of functions. The functions can be defined within the class exactly the same way that functions are normally created. In order to call these functions we need to call it from the class.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ define-and-call-methods-in-a-python-class
Define and Call Methods in a Python Class - GeeksforGeeks
July 23, 2025 - In this article, we will explore the concepts of methods in a class in Python and will see how to define and call methods in a class with examples and explanations. A method in a class is a function that is associated with an object. It defines the behavior and actions that objects of the class can perform. Methods are essential for encapsulating functionality and promoting code reusability. They are defined inside a class and can access the attributes (variables) of the class.
๐ŸŒ
Sada Tech
tech.sadaalomma.com โ€บ python โ€บ how-to-call-a-function-inside-a-class-python
How to Call a Function Inside a Class Python - SADA Tech
February 14, 2024 - We learned that functions defined within a class are called methods, and they can be called using dot notation. We also discussed some best practices and common pitfalls to avoid when calling functions inside classes.
๐ŸŒ
Iditect
iditect.com โ€บ faq โ€บ python โ€บ how-to-call-a-function-within-a-class-in-python.html
How to call a function within a class in python?
In this code, my_function() is a function defined within the class MyClass, and it is called using an instance of the class. ... Description: This query seeks an example demonstrating how to call a method within a class in Python. class MyClass: def my_method(self): print("Inside my_method") # Creating an instance of MyClass obj = MyClass() # Calling my_method() within the class obj.my_method()
Find elsewhere
๐ŸŒ
YouTube
youtube.com โ€บ watch
#61 Function Inside a Class | Python Tutorials for Absolute Beginners | INIT | SELF - YouTube
In this video you will get an example of how to write function inside the class and explanation around init funtion and self parameters in Python.Important L...
Published: June 30, 2022
๐ŸŒ
YouTube
youtube.com โ€บ watch
How To Call A Function From A Class In Python - YouTube
In this python tutorial, I walk you through how to call a function from a class in python! Often time making the transition from straight function calls to c...
Published: September 27, 2022
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 51979302 โ€บ how-to-call-a-function-within-a-class
python - How to call a function within a class? - Stack Overflow
The last comment isn't entirely true. self is just a convention name: it doesn't exactly mean that it's going to be an object or a class for which it's going to be called, and it doesn't even need to be called self 2018-08-23T15:14:14.697Z+00:00 ... def print3() inside the class is just a declaration.
๐ŸŒ
freeCodeCamp
forum.freecodecamp.org โ€บ curriculum help
Accessing inner functions in a class - Curriculum Help - The freeCodeCamp Forum
February 4, 2022 - Hi there! I am a beginner in python so I like to experiment. I was trying object oriented programming when I got stuck on this problem. Here is my code. The problem is in the last line of code. How can I access a nested inner function using object of a class?
๐ŸŒ
pythontutorials
pythontutorials.net โ€บ blog โ€บ calling-a-function-from-class-in-python-different-way
How to Call a Function from a Class in Python: Different Methods Explained for Beginners โ€” pythontutorials.net
class Car: @staticmethod def start_engine(self): # โŒ 'self' in static method print("Engine started") ... Calling methods from a Python class is foundational to OOP.
๐ŸŒ
Quora
quora.com โ€บ How-do-I-use-a-class-function-inside-another-class-function-in-Python
How to use a class function inside another class function in Python - Quora
Answer (1 of 8): You can add a __new__(self) function to your mango object that will return a reference to itself when the class is instantiated. [code]class mango(): def func(): a=8 b=9 return a+b # New method that will return a reference to # itself when object ...
Top answer
1 of 2
1

You have to initialize the class, then only you can call the methods of that class. Also, methods should have it's first argument as self.

class H:
   def y(self):
         print "j"
g = H()
g.y()

Refer here for more details about self.

You should definitely check this chapter for class.

2 of 2
0

You've got answers and comments, so let me explain the error message.

In your code, g and H are different names for the same thing, so the two errors are one.

Now, H is an (old-style) class and all the functions def'ed below it, unless "processed" with tricks like classmethod or staticmethod, are methods. When you access the methods as attributes of the class H, they're known as "unbound" methods because they're not yet bound to an instance of the class H.

To understand how Python's core model of classes, methods, and attributes, I recommend the excellent posts by Shalabh Chaturvedi:

  • Python Types and Objects
  • Python Attributes and Methods

The tl;dr version: normally you're expected to call a method by invoking an instance's bound method:

>>> class H(...):
>>>     def y(...):
>>> h_instance = H()
>>> h_instance.y(...)

Python will put that instance (h_instance here in the fake code snippet) as the first argument to the method. If you call it as h_instance.y(), the actual argument list is (h_instance); if you call it as h_instance.y(a), the arguments are (h_instance, a).

This is why you almost invariably find the first formal argument in a method definition to be self. There's nothing special about this name, except that Python expects that slot be reserved for the instance on which the method is invoked. It allows you to define the method with an empty argument list, but that one wouldn't be useful when you actually use the instance. In that case you'll always get TypeError -- because the call sends ONE argument (the "self" instance) while there's none in the method definition.

As a demonstration, consider the following session:

In [1]: class H(object):    # New-style class, doesn't matter here.
   ...:     def y(self):    # Notice the call signature: "self" included
   ...:         print "j"        

In [2]: h_instance = H()    # Create an instance from the class

# This is how normally you're expected to call. There's no argument
# passed to the *bound* to the instance h_instance, because when you do
# this Python will carry out the syntactic desugaring and call on the
# instance.
In [3]: h_instance.y()
j

# This does the same thing and demonstrates the concept of an
# unbound method.  It's not bound to any specific instance of H, so
# you'll have to specify which instance to call.
In [4]: H.y(h_instance)
j