Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer to the class from within it (like a recursive function)

Tags:

python

class

For a recursive function we can do:

def f(i):   if i<0: return   print i   f(i-1)  f(10) 

However is there a way to do the following thing?

class A:   # do something   some_func(A)   # ... 
like image 986
KL. Avatar asked Jan 09 '10 23:01

KL.


People also ask

How do you reference a class inside a class in Python?

If I understand your question correctly, you should be able to reference class A within class A by putting the type annotation in quotes. This is called forward reference.

Can a class be recursive?

When an object of some class has an attribute value of that same class, it is a recursive object.

What is __ class __ in Python?

__class__ # Output: <class 'type'> Thus, the above code shows that the Human class and every other class in Python are objects of the class type . This type is a class and is different from the type function that returns the type of object.

What is a recursive function in Python?

Python also accepts function recursion, which means a defined function can call itself. Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.


2 Answers

If I understand your question correctly, you should be able to reference class A within class A by putting the type annotation in quotes. This is called forward reference.

class A:   # do something   def some_func(self, a: 'A')   # ... 

See ref below

  1. https://github.com/python/mypy/issues/3661
  2. https://www.youtube.com/watch?v=AJsrxBkV3kc
like image 140
Chin Pang Yau Avatar answered Sep 19 '22 06:09

Chin Pang Yau


In Python you cannot reference the class in the class body, although in languages like Ruby you can do it.

In Python instead you can use a class decorator but that will be called once the class has initialized. Another way could be to use metaclass but it depends on what you are trying to achieve.

like image 37
Anurag Uniyal Avatar answered Sep 20 '22 06:09

Anurag Uniyal