[Python]面向对象编程---实例(3)

三、实例

1、__init__() “构造器”方法

    当类被调用,实例化的第一步是创建实例对象,一旦对象创建了,Python检查是否实现了__init__()方法。

(1) 如果没有定义或覆盖__init__(),则不对实例做任何操作,返回它的对象,实例化过程完毕。

(2) 如果__init__()已经被实现,那么它将被调用,实例对象作为第一个参数self被传递进去。并且调用类时传递的任何参数都交给了__init__()。

构造器__init__()不应当返回任何对象,因为实例对象是自动在实例化调用后返回的。

2、__new__() “构造器”方法

__new__()是一种静态方法,传入的参数是在类实例化操作时生成的。
用来实例化不可变对象,比如派生类、数字等 __new__()会调用父类的__new__()来创建对象。

3、__del__() “解构器”方法 这个函数直到该实例对象所有的引用都被清除后才会执行。 切记__del__()需要先调用父类的__del__()来清除

class P(object):
    pass
class C(P):
    def __init__(self):
        print('initialized')
    def __del__(self):
        P.__del__(self)
        print('deleted')

4、Python没有提供任何内部机制来跟踪一个类有实多少例被创建了,或者记录这些实例是些什么东西。 最好的方法是使用一个静态成员来记录实例的个数,例如:

class InstCt(object):
    count = 0                  # 数据属性
    def __init__(self):
        InstCt.count += 1

    def __del__(self):
        InstCt.count -= 1

    def howMany(self):
        return InstCt.count
>>> a = InstCt()
>>> b = InstCt()
>>> a.howMany()
2
>>> b.howMany()
2
>>> del b
>>> a.howMany()
1
>>> del a
>>> InstCt.count
0

5、查看实例属性

>>> class C(object):
...     pass
...
>>> c = C()
>>> c.foo = 'abcd'
>>> c.bar = 'yes'
>>> dir(c)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar', 'foo']
>>> c.__dict__
{'foo': 'abcd', 'bar': 'yes'}
>>> c.__class__
<class '__main__.C'>  

    原文作者:xl365t
    原文地址: https://blog.csdn.net/u010318270/article/details/70786842
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞