python_类的创建过程

类的创建及分析

1.类属性

class foo(object):

    __num=0   ##定义类属性. 一般用于标记生成实例的多少

类属性只能通过 类.类属性  来访问和更改

2.类方法

使用装饰器来修饰 ,和生成的实例没什么关系,只是类的一个方法.  生成的实例不能调用

    @classmethod  ##定义类方法,类方法是和实例无关的方法.通过 类.类方法 调用
    def shownum(self):
        print("当前实例化的实例个数%d"%foo.__num)

3.__str__(self)

a=foo()
print(a)  ###  __str__

当打印实例对象时,所返回的东西

4.__call__(self):

a=foo()
a()  ### __call__

当把实例对象加上括号时() ,当成函数用的时候 所返回的东西

5.析构方法__del__(self):

当程序执行完成后,会自动调用

析构方法,当对象在内存中被释放时,自动触发执行。

注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的。

#coding:utf-8
import gc
#from memory_profiler import profile

class foo(object):

    __num=0   ##定义类属性. 标记生成实例的多少

    def __call__(self):
        print("call...")

    def __str__(self):
        print("str...")
        return "...<%s>..."%'foo'

    def __init__(self):
        print("新建一个实例")
        foo.__num+=1    ##实例化一个实例,类属性+1

    @classmethod  ##定义类方法,类方法是和实例无关的方法.通过 类.类方法 调用
    def shownum(self):
        print("当前实例化的实例个数%d"%foo.__num)

    def __del__(self):   ##重写析构方法
        print("删除实例")
        foo.__num-=1
        #foo.shownum()

#@profile
def a():
    foo.shownum()
    a=foo()
    a()  ### __call__
    print(a)  ###  __str__
    foo.shownum()
    #a.__del__()
    foo.shownum()
    b=foo()
    foo.shownum()

a()


#结果:
当前实例化的实例个数0
新建一个实例
call...
str...
...<foo>...
当前实例化的实例个数1
当前实例化的实例个数1
新建一个实例
当前实例化的实例个数2
删除实例
删除实例

python中  "一切皆对象"  ,其中类也是对象, 那么类是由谁创建的呢?

>>> class foo():
...     pass
... 
>>> type(foo)
<class 'type'>

以上可以看出, 类的类型为 type .

python中一切皆对象,类也是对象,类是由type类创建的. type也是类,它可以创建类,所以叫它元类

类的另一种创建方式

class Foo(object):
    pass

等价于

Foo = type('Foo', (object,), {})

type()的三个参数:'Foo':类名; (object, ): 类的继承关系,用元组表示; {}: 类的字段,方法。

#示例

def init(self,name):
    self.name = name
    print(self.name)

foo=type('foo',(),{"__init__":init})
#foo=type('foo',(objects,),{"__init__":init})

a=foo("tom")
输出结果
tom

自定义元类控制类的行为

#一个类没有声明自己的元类,默认他的元类就是type,除了使用元类type,用户也可以通过继承type来自定义元类

发布了27 篇原创文章 · 获赞 1 · 访问量 2618

猜你喜欢

转载自blog.csdn.net/bck1453925668/article/details/103242603