About Class

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.








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值