您的位置:首页 > 移动开发 > Objective-C

Exception AttributeError: "'NoneType' object has no attribute错误

2015-07-06 11:29 441 查看
出现:Exception AttributeError: "'NoneType' object has no attribute最近学习《Python参考手册》学到Class部分,遇到了类的构造析构部分的问题:1、什么时候构造?2、什么时候析构?3、成员变量如何处理?4、Python中的共享成员函数如何访问?------------------------探索过程:1、经过查找,Python中没有专用的构造和析构函数,但是一般可以在__init__和__del__分别完成初始化和删除操作,可用这个替代构造和析构。还有一个__new__用来定制类的创建过程,不过需要一定的配置,此处不做讨论。 2、类的成员函数默认都相当于是public的,但是默认开头为__的为私有变量,虽然是私有,但是我们还可以通过一定的手段访问到,即Python不存在真正的私有变量。如:
3、我们可以通过self.__class__访问到类本身,然后再访问自身的共享成员变量,即 self.__class__.num_count , 将类中的NewClass.num_count替换为self.__class__.num_count 编译运行,如下:class Person:
'''Represents a person.'''
population = 0
def __init__(self,name):
'''Initializes the person's data.'''
self.name = name
print '(Initializing %s)' % self.name
Person.population += 1
def __del__(self):
'''I am dying.'''
print '%s says bye.' % self.name
#Person.population -= 1 #开始是这么定义的
self.__class__.population -= 1 ##改为这样就不报错了
if self.__class__.population == 0:
print 'I am the last one.'
else:
print 'There are still %d people left.' % self.__class__.population
def sayHi(self):
print 'Hi, my name is',self.name
def howMany(self):
if Person.population == 1:
print 'I am the only person here.'
else:
print 'We have %d persons here.' % Person.population

swaroop = Person('Swaroop')
swaroop.sayHi()
swaroop.howMany()

kalam = Person('Abdul Kalam')
kalam.sayHi()
kalam.howMany()

swaroop.sayHi()
swaroop.howMany()

书上又提到了一些问题,在这里作补充(仅作为参考): __new__()是唯一在实例创建之前执行的方法,一般用在定义元类时使用。

del xxx 不会主动调用__del__方法,只有引用计数==0时,__del__()才会被执行,并且定义了__del_()的实例无法被Python的循环垃圾收集器收集,所以尽量不要自定义__del__()。一般情况下,__del__() 不会破坏垃圾处理器。 实验中发现垃圾回收自动调用了__del__, 这与书上所说又不符,不知是什么原因,需要继续学习
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: