少说话多写代码之Python学习041——类03(类命名空间 )

栏目: Python · 发布时间: 7年前

内容简介:先看两个函数,实现一个数的平方。输出调用时,squarter和squarter2可以在全局函数模块定义,也可以在局部函数中定义。这样定义的其实都可称作代码块。而我们定义的类,其实是一个特殊的代码块,代码块中的变量,方法

先看两个函数,实现一个数的平方。

def squarter(x):
    return  x*x

squarter2 = lambda  x: x*x

print(squarter(9))
print(squarter2(8))

输出

调用时,squarter和squarter2可以在全局函数模块定义,也可以在局部函数中定义。这样定义的其实都可称作代码块。而我们定义的类,其实是一个特殊的代码块,代码块中的变量,方法

只能被这个类的实例所访问。比如下面我们定义的类,如果需要访问元素只能通过实例访问,且不同的实例都可以访问类里的元素。

class memberCollectCount:
    count=0
    def init(self):
        memberCollectCount.count +=1

m1=memberCollectCount()
m1.init()
print(m1.count)

m2=memberCollectCount()
m2.init()
print(m2.count)

输出

这里是一个执行计数的一个类,每执行init一次,都计数。

再定义个类,

class memberCollectCount2:
    count=0
    def init(self):
        memberCollectCount2.count +=1

都有count和init但是它们属于不同的类,其实也是属于不同的命名空间。

因为 Python 是解释执行的,只有在执行的时候才会有命名空间产生。

工程文件下载: https://download.csdn.net/download/yysyangyangyangshan/10778545


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

High Performance Python

High Performance Python

Micha Gorelick、Ian Ozsvald / O'Reilly Media / 2014-9-10 / USD 39.99

If you're an experienced Python programmer, High Performance Python will guide you through the various routes of code optimization. You'll learn how to use smarter algorithms and leverage peripheral t......一起来看看 《High Performance Python》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

html转js在线工具
html转js在线工具

html转js在线工具