python 特性,函数和方法

#可以将类的特性绑定到一个普通函数上,这样就不会有特殊参数self了
class Class:
    def method(self):
        print('hello,world')
def func():
    print("I'll never give up")
a = Class()
a.method = func
a.method() #返回: I'll never give up
#self参数并不依赖于调用方法的方式,可以随意使用其他变量引用同一个方法
class Bird:
    song = 'Squaawk'
    def sing(self):
        print(self.song)
bird = Bird()
birdsong = bird.sing
birdsong() #返回:'Squaawk'
#为了让方法或者特性变为私有,只要在它的名字前面加上双下划线即可
class Secretive:
    def __inaccessiable(self):
        print("Bet you can't see me")
    def accessiable(self):
        print("The secret message is:")
        self.__inaccessiable()
s = Secretive()
s.__inaccessiable() #报错
#如果确实想访问,可以在方法名之前 加上 “单下划线” 加 “类名”
s._Secretive__inaccessiable() #返回:"Bet you can't see me"
#如果不想使用上述方法,又想让其他对象不要访问内部数据,可以在方法之前加“单下划线”,这样在 from module import * 时,有下划线的名字都不会被导入
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sarah ฅʕ•̫͡•ʔฅ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值