python init new metaclass

在python这个开发语言中同样也有很多特殊的方法,其中__new__是在实例创建之前被调用的,用于创建实例,然后返回该实例对象,是个静态方法。__init__是当实例对象创建完成后被调用的,用于初始化一个类实例,是个实例方法。

python init new 方法都是其构造方法。

__init__方法: init方法通常用在初始化一个类实例的时候.init其实不是实例化一个类的时候第一个被调用的方法。通常来实例化一个类时,最先被调用的方法,其实是new方法。

__new__: new方法接受的参数也是和init一样,但init是在类实例创建之后调用,而new方法也是创建这个类实例的方法

  • init通常用于初始化一个新实例,控制这个初始化的过程,比如添加一些属性,做一些额外的操作,发生在类实例被创建完成之后。它是实例级别的方法
  • new通常用于控制生成一个新实例的过程,他是类级别的方法。
class Animal(object):
    def __init__(self, name, color):
        print('__init__ called')
        self.name = name
        self.color = color

    def __new__(cls, *args, **kwargs):
        print('__new__ called')
        print(args)
        print(kwargs)
        return super(Animal, cls).__new__(cls)

    def __str__(self):
        return '<Animal %s %s>' % (self.name, self.color)

if __name__ == '__main__':
    dog = Animal('Dog', 'red')
    print(dog)

输出结果如下:

__new__ called
('Dog', 'red')
{}
__init__ called
<Animal Dog red>

new方法主要是当你继承一些不可变的class时,如int,str,tuple,提供给你一个自定义这些类的实例化过程的途径,还有就是实现自定义的metaclass。

还可以用new实现设计模式中的单例模式

class SingleModle(object):
    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = super(SingleModle, cls).__new__(cls)
        return cls.instance

if __name__ == '__main__':
    obj1 = SingleModle()
    obj2 = SingleModle()
    obj1.params = 'hello world'
    print(obj1.params)
    print(obj2.params)
    print(obj1 is obj2)

输出结果是

hello world
hello world
True

Metaclass 元类

  • 旧版本的class是来源一个built-in type叫做instance. 如果实例化一个class后得到obj, 那么obj.class会显示它来源于哪个class, 但是type(obj)是instance. 下面的例子env是Python2.7
    class Zoom:
    pass
    z = Zoom()
    print z.__class__
    print type(z)
    #__main__.Zoom
    #<type 'instance'>
  • 新版本的class联合了class和type的概念. 如果obj是一个新版本class的实例, 那么type(obj)和obj.class的返回结果是一样的. 在Python 3中, 所有class都是新版本的class. 有一句话, 那就是在Python中, everything is an object. Class本身也是object
    # 熟悉的built-in class也是type
    for t in int, float, dict, list, tuple:
    print(type(t))
    #<class 'type'>
    #<class 'type'>
    #<class 'type'>
    #<class 'type'>
    #<class 'type'>
    # type本身也是type
    print(type(type))
    #<class 'type'>
  • Zoom()创建了一个class Zoom的实例.
  • Zoom的父class中的call()会被启动, 因为Zoom是新版本的class, 所以它的父class就是type, 所以type的class()方法会被调用.
  • call()方法会调用new()以及init()方法.
  • 如果Zoom没有定义这两个方法, 会使用Zoom的祖先中的这两个方法.
  • 如果Zoom定义了这两个方法, 会覆盖祖先中的这两个方法
class Zoom:
    pass
z = Zoom()
print(z.__class__)
print(type(z))
print(type(Zoom))

#<class '__main__.Zoom'>
#<class '__main__.Zoom'>
#<class 'type'>
1. z是Zoom的实例
2. Zoom是type的实例
3. type是type的实例
  • type是一个metaclass, class是实例. 在Python 3中, 任何class都是type这个metaclass的实例

使用type定义class

  • 使用type创建class. 英文上说叫dynamically创建class
  • 用type创建class时有三个参数(, , )
    1. name指的就是class的名字, 它会变成class.name
    2. bases指的是这个class的祖先
    3. dct指的是class定义的一些method, attribute啥的
def f(self):
    print('in f and attr =', self.attr)
    # return self.attr

Zoom = type(
    'Zoom',
    (),
    {
        'attr': 100,
        'attr_val': f
    }
)

z=Zoom()
print(z.attr)
print(z.attr_val())

常规的定义方式

def fn(self, name = 'world'): #先定义一个函数
    print('Hello, %s' % name)

Hello = type('Hello', (object, ), dict(hello=fn)) #创建Hello class,传入class的名称,继承的父类集合class的方法名与函数绑定,这里我们把fn绑定到hello上

h = Hello()
h.hello()
print(type(Hello))
print(type(h))

#Hello, world
#<class 'type'>
#<class '__main__.Hello'>

type作为元类(Metaclass)被继承

Myclass要继承自type, MyClass这个class本身的创建也需要type, type中的一些方法也会在创建class时用到, 不想把type的所有方法都实现, 只是想做一些基于它的自定义. 这里定义了new这个方法, 我们会打印所有的attrs, 这个方法所需要的三个参数其实跟刚刚type中的三个参数是一样的.

class MyClass(type):
    def __new__(self, class_name, bases, attrs):
        modified = {}
        for name, value in attrs.items():
            if name.startswith("__"):
                modified[name] = value
            else:
                modified[name.upper()] = value
        return type(class_name, bases, modified)

class SonClass(metaclass=MyClass):
    color = "Red"
print(dir(SonClass))

vscode 指定anaconda方式

vscode是一种简化且高效的代码编辑器,同时支持诸如调试,任务执行和版本管理之类的开发操作。它的目标是提供一种快速的编码编译调试工具。然后将其余部分留给IDE。vscode集成了所有一款现代编辑器所应该具备的特性,包括语法高亮、可定制的热键绑定、括号匹配、以及代码片段收集等。

vscode是一种简化且高效的代码编辑器,同时支持诸如调试,任务执行和版本管理之类的开发操作。它的目标是提供一种快速的编码编译调试工具。然后将其余部分留给IDE。vscode集成了所有一款现代编辑器所应该具备的特性,包括语法高亮、可定制的热键绑定、括号匹配、以及代码片段收集等。

Anaconda是专注于数据分析、能够对包和环境进行管理的Python发行版本,包含了conda、Python等多个科学包及其依赖项。conda 是开源包(packages)和虚拟环境(environment)的管理系统

  • 先在本地环境中安装anaconda和vscode
  • vscode安装python插件,新版本的管理设置在左下方齿轮状的图片
  • win系统使用快捷键 CTRL+P的按钮打开搜索,然后输入:> select interpreter
  • Mac系统使用Command+p打开搜索

> select interpreter

⚠️注意: 向左箭头也是要输入的 关键字

  • 弹出如下页面后,请自行选择自己想要的anaconda环境,双击F5运行。

pandas dataframe for loop 循环初探

DataFrame直接使用for循环时,按以下顺序获取列名;使用iteritems()方法,可以获取列名称和pandas.Series类型的元组,元组对应每个列的数据;使用iterrows()方法,可以获得每一行的数据(pandas.Series类型)和列名与具体值的元组

pandas dataframe 是表格型的数据结构,它含有一组有序的列,每列可以是不同的值类型。具体的介绍不做细说,直奔中心问题,一个dataframe怎么做循环?

以下面代码实例为具体介绍,从代码中我们可以看到dataframe的具体创建方式之一,而且是指定了index,当然我们可以不指定index而是通过后续的set index来修改index的值,这些操作我们可以通过之前的篇幅来具体了解。

import pandas as pd

df = pd.DataFrame({'age': [24, 42, 18, 60],
                   'location': ['beijing', 'shanghai', 'beijing', 'shenzhen'],
                   'score': [74, 92, 88, 99],
                   'name': ['huahua', 'mingming', 'laowang', 'xiaowang']},
                  index=['1', '2', '3', '4'])
print(df)
   age  location      name  score
1   24   beijing    huahua     74
2   42  shanghai  mingming     92
3   18   beijing   laowang     88
4   60  shenzhen  xiaowang     99

直接对dataframe做for loop 或者 调用__iter__

直接对dataframe做for循环和调用它的__iter__()方法效果是一样的。都是顺序获取列名。

for d in df:
    print(d)
    print("=====")
for d in df.__iter__():
    print(d)
    print("============")
age
=====
location
=====
name
=====
score

DataFrame.iteritems() 逐列检索

使用iteritems()方法,可以获取列名称和pandas.Series类型的元组,元组对应每个列的数据;

for d in df.iteritems():
    print(d)
    print(type(d))
    print("=========")

我们截取部分输出可以看到,iteritems循环得到的是一个个的tupel对象,而tuple第一个值是str类型的对应的列名称;tuple的第二个值是一个pandas.Series类型的对象,报名此列所有行的索引值以及其具体的列值

('age', 1    24
2    42
3    18
4    60
Name: age, dtype: int64)
<class 'tuple'>
=========
('location', 1     beijing
2    shanghai
3     beijing
4    shenzhen
Name: location, dtype: object)
<class 'tuple'>
=========
dataframe iteritems方法循环

DataFrame.iterrows() 逐行检索

使用iterrows()方法,可以获得每一行的数据(pandas.Series类型)和列名与具体值的元组

for d in df.iterrows():
    print(d)
    print(type(d))
    print("=========")

同样我们从部分的输出结果可以看出来,iterrows的效果是和iteritems相对的。iterrows方法返回的依旧是一个tuple对象,而tuple的第一个值是对应的该行所对应的index值,而tuple第二个值依旧是一个pands.Series类型的对象,该Series包含的此行对应所有列的列名及其具体的值。

('1', age              24
location    beijing
name         huahua
score            74
Name: 1, dtype: object)
<class 'tuple'>
=========
('2', age               42
location    shanghai
name        mingming
score             92
Name: 2, dtype: object)
<class 'tuple'>
=========

其实dataframe还有其它的循环方法,具体的内容此篇不去复述了,平时我们处理数据用到比较多的就是以上几种情况。