返回介绍

01. Python 工具

02. Python 基础

03. Numpy

04. Scipy

05. Python 进阶

06. Matplotlib

07. 使用其他语言进行扩展

08. 面向对象编程

09. Theano 基础

10. 有趣的第三方模块

11. 有用的工具

12. Pandas

super() 函数

发布于 2022-09-03 20:46:14 字数 7261 浏览 0 评论 0 收藏 0

super(CurrentClassName, instance)

返回该类实例对应的父类对象。

In [1]:

class Leaf(object):
    def __init__(self, color="green"):
        self.color = color
    def fall(self):
        print "Splat!"

class MapleLeaf(Leaf):
    def change_color(self):
        if self.color == "green":
            self.color = "red"
    def fall(self):
        self.change_color()
        super(MapleLeaf, self).fall()

这里,我们先改变树叶的颜色,然后再找到这个实例对应的父类,并调用父类的 fall() 方法:

In [2]:

mleaf = MapleLeaf()

print mleaf.color
mleaf.fall()
print mleaf.color
green
Splat!
red

回到我们的森林例子,这里我们将森林 Forest 作为父类,并定义一个子类 BurnableForest

In [3]:

import numpy as np

class Forest(object):
    """ Forest can grow trees which eventually die."""
    def __init__(self, size=(150,150), p_sapling=0.0025):
        self.size = size
        self.trees = np.zeros(self.size, dtype=bool)
        self.p_sapling = p_sapling

    def __repr__(self):
        my_repr = "{}(size={})".format(self.__class__.__name__, self.size)
        return my_repr

    def __str__(self):
        return self.__class__.__name__

    @property
    def num_cells(self):
        """Number of cells available for growing trees"""
        return np.prod(self.size)

    @property
    def tree_fraction(self):
        """
 Fraction of trees
 """
        num_trees = self.trees.sum()
        return float(num_trees) / self.num_cells

    def _rand_bool(self, p):
        """
 Random boolean distributed according to p, less than p will be True
 """
        return np.random.uniform(size=self.trees.shape) < p

    def grow_trees(self):
        """
 Growing trees.
 """
        growth_sites = self._rand_bool(self.p_sapling)
        self.trees[growth_sites] = True    

    def advance_one_step(self):
        """
 Advance one step
 """
        self.grow_trees()
  • 将与燃烧相关的属性都被转移到了子类中去。
  • 修改两类的构造方法,将闪电概率放到子类的构造方法上,同时在子类的构造方法中,用 super 调用父类的构造方法。
  • 修改 advance_one_step(),父类中只进行生长,在子类中用 super 调用父类的 advance_one_step() 方法,并添加燃烧的部分。

In [4]:

class BurnableForest(Forest):
    """
 Burnable forest support fires
 """    
    def __init__(self, p_lightning=5.0e-6, **kwargs):
        super(BurnableForest, self).__init__(**kwargs)
        self.p_lightning = p_lightning        
        self.fires = np.zeros((self.size), dtype=bool)

    def advance_one_step(self):
        """
 Advance one step
 """
        super(BurnableForest, self).advance_one_step()
        self.start_fires()
        self.burn_trees()

    @property
    def fire_fraction(self):
        """
 Fraction of fires
 """
        num_fires = self.fires.sum()
        return float(num_fires) / self.num_cells

    def start_fires(self):
        """
 Start of fire.
 """
        lightning_strikes = (self._rand_bool(self.p_lightning) & 
            self.trees)
        self.fires[lightning_strikes] = True

    def burn_trees(self):
        """
 Burn trees.
 """
        fires = np.zeros((self.size[0] + 2, self.size[1] + 2), dtype=bool)
        fires[1:-1, 1:-1] = self.fires
        north = fires[:-2, 1:-1]
        south = fires[2:, 1:-1]
        east = fires[1:-1, :-2]
        west = fires[1:-1, 2:]
        new_fires = (north | south | east | west) & self.trees
        self.trees[self.fires] = False
        self.fires = new_fires

测试父类:

In [5]:

forest = Forest()

forest.grow_trees()

print forest.tree_fraction
0.00284444444444

测试子类:

In [6]:

burnable_forest = BurnableForest()

调用自己和父类的方法:

In [7]:

burnable_forest.grow_trees()
burnable_forest.start_fires()
burnable_forest.burn_trees()
print burnable_forest.tree_fraction
0.00235555555556

查看变化:

In [8]:

import matplotlib.pyplot as plt

%matplotlib inline

forest = Forest()
forest2 = BurnableForest()

tree_fractions = []

for i in range(2500):
    forest.advance_one_step()
    forest2.advance_one_step()
    tree_fractions.append((forest.tree_fraction, forest2.tree_fraction))

plt.plot(tree_fractions)

plt.show()

https://www.wenjiangs.com/wp-content/uploads/2022/docimg20/vZug1pIJ4BuNntH3-T76LTk.png alt="">

__str____repr__self.__class__ 会根据类型不同而不同:

In [9]:

forest

Out[9]:

Forest(size=(150, 150))

In [10]:

forest2

Out[10]:

BurnableForest(size=(150, 150))

In [11]:

print forest
Forest

In [12]:

print forest2
BurnableForest

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文