#可以将类的特性绑定到一个普通函数上,这样就不会有特殊参数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 * 时,有下划线的名字都不会被导入