码迷,mamicode.com
首页 > 编程语言 > 详细

python基础学习日志day7-类的起源

时间:2017-06-04 22:41:33      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:生成   创建对象   属性   elf   tac   ret   自定义   init   基础学习   

Python中一切事物都是对象。

class Foo(object):
 
 
    def __init__(self,name):
        self.name = name
 
 
f = Foo("alex")

f对象是FOO类的一个实例,Foo类对象是type类的一个实例。

print(type(f))

print(type(foo))

# -*- coding:utf-8 -*-
__author__ = shisanjun

class Foo(object):

    def func(self):
        print("hello world")

f=Foo()

print(type(f))
print(type(Foo))

"""
<class ‘__main__.Foo‘>
<class ‘type‘>
"""

def func(self):
    print("特别定义")

f1=type("Foo1",(object,),{"func":func})
print(type(f1))

类默认是由 type 类实例化产生,type类中如何实现的创建类?类又是如何创建对象?

答:类中有一个属性 __metaclass__,其用来表示该类由 谁 来实例化创建,所以,我们可以为 __metaclass__ 设置一个type类的派生类,从而查看 类 创建的过程。

技术分享

类的生成 调用 顺序依次是 __new__ --> __init__ --> __call__

class MyType(type):
    def __init__(self,*args,**kwargs):

        print("Mytype __init__",*args,**kwargs)

    def __call__(self, *args, **kwargs):
        print("Mytype __call__", *args, **kwargs)
        obj = self.__new__(self)
        print("obj ",obj,*args, **kwargs)
        print(self)
        self.__init__(obj,*args, **kwargs)
        return obj

    def __new__(cls, *args, **kwargs):
        print("Mytype __new__",*args,**kwargs)
        return type.__new__(cls, *args, **kwargs)

print(here...)
class Foo(object,metaclass=MyType):


    def __init__(self,name):
        self.name = name

        print("Foo __init__")

    def __new__(cls, *args, **kwargs):
        print("Foo __new__",cls, *args, **kwargs)
        return object.__new__(cls)

f = Foo("Alex")
print("f",f)
print("fname",f.name)

自定义元类

 

python基础学习日志day7-类的起源

标签:生成   创建对象   属性   elf   tac   ret   自定义   init   基础学习   

原文地址:http://www.cnblogs.com/lixiang1013/p/6941979.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!