How do I use in private function?
private function to public?
def __print(str):
print(str)
class Test():
def print(self, str):
# global __print (same NameError)
__print(str)
t = Test()
t.print("Hi")
NameError: name '_Test__print' is not defined
CodePudding user response:
There is no "private function" Python doesn't really have access modifiers.
If you want to signal that a function isn't part of the public interface, conventionally, a single underscore is used:
def _print(str_):
print(str_)
class Test:
def print(self, str_):
# No error! Idiomatic!
_print(str_)
t = Test()
t.print("Hi")
This would be the idiomatic way of doing this. Python programmers would recognize this.
The problem with your code is that you used two underscores. So now, anytime you try to use that identifier in a class definition, that identifier is mangled by the compiler. Two underscores are for name mangling. This exist for the sole purpose of preventing name collisions in subclasses. And basically it mangles all names defined in the context of a class definition:
Any identifier of the form
__spam
(at least two leading underscores, at most one trailing underscore) is textually replaced with_classname__spam
, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.
You could just use:
_Test__print
So:
class Test:
def print(self, str_):
# No error! Idiomatic!
_Test__print(str_)
And you could (but shouldn't, and should just use a single underscore) do something like:
def __print(str_):
print(str_)
class Test:
pass
def print(self, str_):
# global __print (same NameError)
__print(str_)
Test.print = print
del print # since we polluted the global namespace
t = Test()
t.print("Hi")
You could come up with any manner of workarounds, the point is, you shouldn't do it.