Python Dynamic Add Class method

Source: Internet
Author: User

Exercises:

1. Shape base class, requires that all subclasses must provide the calculation of the area, the subclass has triangles, rectangles, circles.

2. The data of the Circle class can be serialized

The first method: to mix the properties and methods of other classes with mixin multiple inheritance combinations

The second approach: using adorners to decorate classes, adding properties and methods dynamically

Instance:

Import mathimport jsonimport msgpackimport pickleclass Shape: "" Prevents direct calls to the area method of the parent class "" @property def Area (self):        Raise Notimplementederror (' base class not implemented ') class Triangle (Shape): "" "Triangle" "" Def __init__ (self,a,b,c): SELF.A = a self.b = b SELF.C = c @property def area (self): p = (SELF.A+SELF.B+SELF.C)/2 return math. sqrt (p* (P-SELF.A) * (p-self.b) * (P-SELF.C)) class Rectangle (Shape): "" "" "" "" Def __init__ (self,width,height): Sel F.width = width Self.height = height @property def area (self): return self.width * self.heightdef Seri            Alizablecircle (CLS): "" "1. Adorners Add Dumps Method" "" # Print (CLS) def dumps (self,t= ' JSON ') for class dynamically: if T = = ' json ':        Return Json.dumps (self.__dict__) elif t = = ' Msgpack ': Return msgpack.packb (self.__dict__)        elif t = = ' pickle ': with open (' Dump.txt ', ' WB ') as F:return pickle.dump (self.__dict__,f) Else:raise NOtimplementederror (' serialization not implemented ') Cls.dumps = dumps return cls@serializablecircle # circle=serializablecircle (CIRCL E) class Circle (Shape): "" "" "" "" "" "__init__" (Self,radius): Self.radius = Radius @property def area ): Return (Self.radius * 2) * Math.PI # def dumps (self,t= ' json '): # if T = = ' json ': # return Json.dumps (self.__dict__) # elif T = = ' Msgpack ': # return MSGPACK.PACKB (self.__dict__) # elif t = = ' Pickle ': # with open (' Dump.txt ', ' WB ') as F: # return Pickle.dump (self.__dict__,f) # El SE: # Raise Notimplementederror (' serialization not Implemented ') # SC = Circle (4) # sc.dumps (' Pickle ') class Serializablemixin: "" "Order List "" "Def dumps (self,t= ' json '): if t = = ' json ': Return Json.dumps (self.__dict__) elif t = = ' ms  Gpack ': Return msgpack.packb (self.__dict__) elif t = = ' pickle ': with open (' Dump.txt ', ' WB ') as F:return Pickle.dump (self.__dict__,f) else:raise notimplementederror (' serialization not implemented ') def loads (self,t= ' json '): Passclass serializablecirclemixin (serializablemixin,circle): "" "2.Mixin combination dynamically adds dumps method" "" Passshapes = [Tria] for class Ngle (3,4,5), Rectangle (3,4), Circle (4)]for s in Shapes:print (' the area of {} = {} '. Format (S.__class__.__name__,s.area) ) #Mixinscm = serializablecirclemixin (4) print (Scm.area) s = scm.dumps (' Msgpack ') print (s) #装饰器sc = Circle (4) s = Sc.dumps (' JSON ') print (s)

  

Python Dynamic Add Class method

Related Article

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.