我要一大群的类都具有一中特点,我怎么给他们加上呢?模板模板吗,我从这个模板创建一群类不就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的尝试失败了,而这恰恰证明我们成功了。
其实元类用的不多,理解理解。霍霍!!

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.


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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Atom editor mac version download
The most popular open source editor

SublimeText3 English version
Recommended: Win version, supports code prompts!
