Emulate a class using a dictionary in Python

Source: Internet
Author: User

Using a dictionary in Python to emulate a class, here's a simple example

defNewclass (* *Kwargs):"""using the Kwargs Update () method to handle inheritance issues"""    defset (key, value): Kwargs[key]=value kwargs['Set'] =SetreturnKwargsdefMammal (* *Kwargs):"""Mammalian base class"""    #handling inheritance issues is equivalent to __init__ ()kwargs.update (Newclass ())#mammals have four legs, the equivalent of a propertykwargs['Legs'] = 4#Equivalent Method    defsay ():return "There's no such method ."    #Equivalent Method    defeat ():return "There's no such method ."    #using lambdakwargs['say'] =say kwargs['Eat'] =EatreturnKwargsdefCat (* *Kwargs):Print("the parameters obtained", Kwargs) kwargs.update (Mammal ())defsay ():return "Meow Meow"kwargs['say'] =sayreturnKwargsmammal=mammal ()#The method property is no longer used with the object. Methods and objects. property instead use [] instead. Print(mammal['say']())Print(mammal['Eat']())Print(mammal['Legs']) CAT1=Cat ()Print(cat1['say']())Print(cat1['Legs'])Print(cat1['Eat']())#print ("CAT1 hair color is:", cat1[' Red '])D= {"Color":"Red","Legs": 3}#Setting PropertiesCAT2 = Cat (* *d)#Calling MethodsPrint(cat2['say']())#Read PropertiesPrint(cat2['Legs'])#Calling MethodsPrint(cat2['Eat']())Print("the color of the hairs is:", cat2['Red'])

Emulate a class using a dictionary in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.