1) method and function
One big difference between methods and other functions is that methods always receive the object they are part of as their first argument, usually called self.
>>> class Class:
def method(self):
print 'I have a self!'
>>> def function():
print "I don't..."
>>> instance = Class()
>>> instance.method()
I have a self!
>>> instance.method = function
>>> instance.method()
I don't...
You're free to use another variable that refers to the same method:
>>> class Bird:
song = 'Squaawk!'
def sing(self):
print self.song
>>> bird = Bird()
>>> bird.sing()
Squaawk!
>>> birdsong = bird.sing
>>> birdsong()
Squaawk!
Even though the last method call looks exactly like a function call, the variable birdsong refers to the bound method bird.sing, which means that it still has access to the self parameter
(that is, it is still bound to the same instance of the class).
After you read the following section, you will see python is so open!
2)class privacy
Python doesn't support privacy directly, but relies on the programmer to know when it is safe to modify an attribute from the outside.It is, however, possible to achieve something like private attributes with a little trickery.To make a method or attribute private (inaccessible from the outside), simply start its name with two underscores:
class Secretive:
def __inaccessible(self):
print "Bet you can't see me..."
def accessible(self):
print "The secret message is:"
self.__inaccessible()
Now __inaccessible is inaccessible to the outside world, while it can still be used inside the class (for example, from accessible):
>>> s = Secretive()
>>> s.__inaccessible()
Traceback (most recent call last):
File "<pyshell#112>", line 1, in ?
s.__inaccessible()
AttributeError: Secretive instance has no attribute '__inaccessible'
>>> s.accessible()
The secret message is:
Bet you can't see me...
Although the double underscores are a bit strange, this seems like a standard private method, as found in other languages.
What's not so standard is what actually happens. Inside a class definition, all names beginning with a double underscore are "translated" by adding a
single underscore and the class name to the beginning:
>>> s._Secretive__inaccessible()
Bet you can't see me...
So, in short, you can't be sure that others won't access the methods and attributes of your objects, which make me worry the security of python and curious about how pyhon figure it out
,but this sort of name-mangling is a pretty strong signal that they shouldn't.