You don't need to reference the class inside itself, using bar instead of Test.bar will work fine.
class Test:
@staticmethod
def bar():
pass
FOO_DICT = {1: bar}
# You can access this outside of the class by simply using Test.FOO_DICT
print(Test.FOO_DICT)
However, there are cases where you really need to use a class in itself. For example
class Test:
@staticmethod
def bar():
pass
def test_with_other_of_same_instance(self, other: Test):
print(other.FOO_DICT)
FOO_DICT = {1: bar}
In this case,
- I want to define a method that accepts an object of the same Test class.
- I want to use python's type hinting to indicate that the expected argument is an instance of Test. This allows me get editor support and also so tools like pylance and mypy can notify me of possible errors if I passed a argument of wrong data type.
As at the time of this writing, I'll get a NameError: name 'Test' is not defined.
This is because by default I can't use a class within itself (It is possible later versions of python will change its default behavior, hence we won't be needing the solution below by that time).
But if you use Python versions from 3.7+ and you can't reference a class within itself, the simple solution came with PEP 563 - Postponed evaluation of annotations. It is implemented by adding a little line of code at the first line of the file
from __future__ import annotations
# other imports or code come afterwards
class Test:
@staticmethod
def bar():
pass
def test_with_other_of_same_instance(self, other: Test):
print(other.FOO_DICT)
FOO_DICT = {1: bar}
So you can use a class within itself in python by simply including that line at the beginning of the file.
Normally, if you use pylance or any similar tool, you get a warning or error display to show you that you imported something and didn't use it. But not in the case of annotations. You don't have to worry about any warning from your editor.
Note that this must occur at the beginning of the file otherwise you get a SyntaxError and versions earlier than 3.7 won't support this.
Answer from Victory Ifebhor on Stack OverflowYou don't need to reference the class inside itself, using bar instead of Test.bar will work fine.
class Test:
@staticmethod
def bar():
pass
FOO_DICT = {1: bar}
# You can access this outside of the class by simply using Test.FOO_DICT
print(Test.FOO_DICT)
However, there are cases where you really need to use a class in itself. For example
class Test:
@staticmethod
def bar():
pass
def test_with_other_of_same_instance(self, other: Test):
print(other.FOO_DICT)
FOO_DICT = {1: bar}
In this case,
- I want to define a method that accepts an object of the same Test class.
- I want to use python's type hinting to indicate that the expected argument is an instance of Test. This allows me get editor support and also so tools like pylance and mypy can notify me of possible errors if I passed a argument of wrong data type.
As at the time of this writing, I'll get a NameError: name 'Test' is not defined.
This is because by default I can't use a class within itself (It is possible later versions of python will change its default behavior, hence we won't be needing the solution below by that time).
But if you use Python versions from 3.7+ and you can't reference a class within itself, the simple solution came with PEP 563 - Postponed evaluation of annotations. It is implemented by adding a little line of code at the first line of the file
from __future__ import annotations
# other imports or code come afterwards
class Test:
@staticmethod
def bar():
pass
def test_with_other_of_same_instance(self, other: Test):
print(other.FOO_DICT)
FOO_DICT = {1: bar}
So you can use a class within itself in python by simply including that line at the beginning of the file.
Normally, if you use pylance or any similar tool, you get a warning or error display to show you that you imported something and didn't use it. But not in the case of annotations. You don't have to worry about any warning from your editor.
Note that this must occur at the beginning of the file otherwise you get a SyntaxError and versions earlier than 3.7 won't support this.
If you want the dictionary to be in the class: define the function first and remove Test:
class Test:
@staticmethod
def bar():
pass
FOO_DICT = {1: bar}
Update
In Python 3.11 the module is named typing instead of typing_extensions
from typing import Self
class Node:
"""Binary tree node."""
def __init__(self, left: Self, right: Self):
self.left = left
self.right = right
This might be helpful:
from typing_extensions import Self
class Node:
"""Binary tree node."""
def __init__(self, left: Self, right: Self):
self.left = left
self.right = right
typing_extensions offers a Self class to reference class itself which I think is most elegent way to self-reference(PEP 673).
As others have mentioned, you can also use string literals. But it comes to problem when you have multiple type hints.
# python 3.10
var: str | int
And then you write something like
class Node:
def __init__(self, var: 'Node' | SomeClass):
self.var = var
It will raise a TypeError: unsupported operand type(s) for |: 'str' and 'type'.
While this, as other answers have pointed out, is not a problem due to the dynamic typing, in fact, for Python3, this is a very real issue when it comes to type annotations. And this will not work (note a type annotation of the method argument):
class A:
def do_something_with_other_instance_of_a(self, other: A):
print(type(other).__name__)
instance = A()
other_instance = A()
instance.do_something_with_other_instance_of_a(other_instance)
results in:
def do_something_with_other_instance_of_a(self, other: A):
NameError: name 'A' is not defined
more on the nature of a problem here: https://www.python.org/dev/peps/pep-0484/#the-problem-of-forward-declarations
You can use string literals to avoid forward references

Other way is NOT using python3-style type annotation in such cases,
and this is the only way if you have to keep your code compatible with earlier versions of Python.
Instead, for the sake of getting autocompletion in my IDE (PyCharm), you can docstrings like this:

Update: alternatively, instead of using docstrings, you can use "type: " annotations in a comment. This will also ensure that mypy static type checking will work (mypy doesn't seem to care about docstrings):

python - How to refer to the class from within it (like a recursive function) - Stack Overflow
Type of the same class inside the class
python - What is the best way for a class to reference itself in a class attribute? - Stack Overflow
How does “self” in a class work?
You need @classmethod rather than @staticmethod - a class method will get passed a reference to the class (where a method will get self), so you can look up attributes on it.
class FooBarBaz:
BAR = 123
@classmethod
def getBar(cls):
return cls.BAR
Actually, there is __class__ in python 3:
Python 3.2.3 (v3.2.3:3d0686d90f55, Apr 10 2012, 11:25:50)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
... @staticmethod
... def foo():
... print(__class__)
...
>>> A.foo()
<class '__main__.A'>
>>>
See http://www.python.org/dev/peps/pep-3135 for the rationale why it has been added.
No idea about how to achieve the same in py2, I guess this is not possible.
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
- https://github.com/python/mypy/issues/3661
- https://www.youtube.com/watch?v=AJsrxBkV3kc
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.
Use a meta class to automatically set it.
def my_meta(name, bases, attrs):
cls = type(name, bases, attrs)
cls.bar = cls
return cls
class Foo(object):
__metaclass__ = my_meta
>>> print Foo.bar
<class '__main__.Foo'>
You could define a class decorator that replaced placeholder strings with the class being defined:
def fixup(cls):
placeholder = '@' + cls.__name__
for k,v in vars(cls).items():
if v == placeholder:
setattr(cls, k, cls)
return cls
@fixup
class Foo(object):
bar = '@Foo'
print('Foo.bar: {!r}'.format(Foo.bar)) # -> Foo.bar: <class '__main__.Foo'>
Another alternative would be to use the __init_subclass__() special method which was introduced in Python 3.6 to create a base class and then derive your class from it instead of the generic object:
class Base(object):
def __init_subclass__(cls, /, **kwargs):
super().__init_subclass__(**kwargs)
cls.bar = cls
class Foo(Base):
pass
print('Foo.bar: {!r}'.format(Foo.bar)) # -> Foo.bar: <class '__main__.Foo'>
You have to add “self” as an argument to a class method. Why this specific syntax and how does it get interpreted? Is this because it inherits from the Python object model?
Is there any language where public methods do not contain “self” as an argument?
Thank you
I have a class with a method called "edit", and I want to make another method called "overlay" that uses the edit method inside itself, Is that possible?
Karl's answer is entirely right about everything, but there is certainly a way to make resize act as you're expecting.
Three steps:
- Make a copy of the tree
- Re-initialize the tree so it's the next size larger
Set the enlarged tree's
leftto the copy of the original treedef resize(self,n): while self.size < n: new = self.copy() self.__init__(int(round(self.size, 2)) * 2) self.left = new print("size in resize",self.size) def copy(self): new = tree(1) new.left = self.left new.right = self.right new.size = self.size new.free = self.free return new
Basically, you were trying to do it backwards -- replace self and reuse self for self.left, instead of replacing self.left and reusing self.
self = t
This does not, and cannot be rewritten to, do what you want. There is nothing "special" about the name self in Python; it's just like any other variable (the fact that you have to pass it explicitly to methods should have been your first hint, unlike in languages that treat this as a keyword, should have been your first hint ;) ), and like all other variables, it has reference semantics.
self = t means "from this point onward (until another re-definition or the end of scope), self no longer refers to what that self parameter referred to, but instead to the value that t refers to".
Also, you have a typo in one case of your __init__ method ('rigt'), and I assume that the number of free nodes is supposed to be an invariant something like size - occupied; in which case it would be cleaner to count the occupied nodes and use a method or property to calculate the free ones, instead of trying to update that count on every modification.
(Moreover, what you seem to be trying to do is all kinds of un-Pythonic. In particular, the idea of a container having a specific "allocated size" is strange; that sort of thing normally only matters on the C side of the fence. What do you need a binary tree for? Also, this method isn't going to balance the tree at all. And what use is a tree if none of the nodes store any data?)
Add the class after the class is defined:
class Template():
_allowed_types = [str, SafeHtml]
Template._allowed_types.append(Template)
The class body, by necessity, is run before the class object can be created, so the name Template is not defined yet. But you can always alter class attributes after the object has been created.
Another option is using properties to be lazy about the field.
class Test(object):
@property
def allowed(self):
return [str, Test]
t = Test()
print Test in t.allowed