Python 元类使用说明
我要一大群的类都具有一中特点,我怎么给他们加上呢?模板模板吗,我从这个模板创建一群类不就OK了?那就需要元类了。霍霍》
定义一个元类(就所一个类的模板!莫多想,还要记住这是类级别的,不是对象级别的!):
class MyMeta(type):
def __init__(cls,name,bases,dic):
print cls.__name__
print name
def __str__(cls):return 'Beautiful class %s'%cls.__name__
这是个什么东西?哈,这是个元类。是个类的模板。
它要用在哪里?它要用在一个类里,作为这个类的模板。
起的什么作用?模板,就是提供一些共同的特征。
这个类提供了什么样的特征?两个特征,1。类定义后打印类的名字(__init__)。2。打印类的格式(__str__)。
到底回怎么工作,打开的你的解释器,输入以上的代码,上路:
输入:
class MyClass(object):
__metaclass__ = MyMeta
回车结束类的定义时,输出:
MyClass
MyClass
明白了吧,霍霍!事实证明它确实是初始化一个类,而不是一个对象!!!!!这个是第一个特征。
第二个:
输入:
print MyClass
输出:
Beautiful class MyClass
啊哈,恰如其分,如我们所预料的那样!!!!!!!!当然你可以任意个性化你的类!!
####################################################################################
下面我们来实现一个Singleton模式(来自啄木鸟社区):
Singleton元类:
class Singleton(type):
def __init__(cls,name,bases,dic):
super(Singleton,cls).__init__(name,bases,dic)
cls.instance = None
def __call__(cls,*args,**kwargs):
if cls.instance is None:
cls.instance = super(Singleton,cls).__call__(*args,**kwargs)
return cls.instance
非常简单的一个设计模式,相信你能明白是怎么回事!
class MyClass(object):
__metaclass__ = Singleton
def __init__(self,arg):
self.arg = arg
使用了Singleton元类的类。
是不是只能有一个实例呢??那只能看看了,邓爷爷说的好:实践是检验真理的唯一标准。——精华!!
>>> my1 = MyClass("hello")
>>> my2 = MyClass("world")
>>> my1 is my2
True
>>> my1.arg
'hello'
>>> my2.arg
'hello'
我们创建my2的尝试失败了,而这恰恰证明我们成功了。
其实元类用的不多,理解理解。霍霍!!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
