PYTHON,实例用做属性问题

2025-06-27 04:35:26
推荐回答(1个)
回答1:

以双下划线__开头的变量是内部变量,只能在内部引用。举个栗子:
12345678910111213>>> class a(object):... def __init__(self):... self.__n=3... def p(self):... print self.__n...>>> b=a()>>> b.__nTraceback (most recent call last): File "", line 1, in AttributeError: 'a' object has no attribute '__n'>>> b.p()3
而你的全局函数print_score,就是这部分:
1234def print_score(self): print '%s : %s' % (self.__name,self.__score) #print 'age : %s ' % self.ageaa.print_score = MethodType(print_score,aa,Student)
这样做替代了Student类中的同名函数。不过看起来它依然不能操作内部变量。去掉下划线就能运行了。