Python Black Magic Collection

Source: Internet
Author: User

Black Magic Collection for the creation of classes omit self
From types import functiontypefrom byteplay import Code, Opmapdef metaclassfactory (function): Class Metaclass (Type):                def __new__ (Meta, classname, bases, classdict): For AttributeName, attribute in Classdict.items (): If type (attribute) = = Functiontype:attribute = function (attribute) newclassdict [AttributeName] = attribute return type.__new__ (meta, classname, bases, classdict) return metaclassdef _tra nsmute (opcode, arg): if ((opcode = = opmap[' Load_global ') and (arg = = ' self '): return opmap[' Load_fast ') , arg return opcode, argdef selfless (function): Code = Code.from_code (function.func_code) Code.args = tuple ([' Sel F '] + list (Code.args)) Code.code = [_transmute (OP, Arg) for OP, arg in code.code] Function.func_code = Code.to_code ( return functionselfless = Metaclassfactory (selfless) class Test (object): __metaclass__ = selfless def __init__ (x =none): self.x =x def getX (): Return self.x def setX (x): self.x = Xtest = Test () print (Test.getx ()) Test.setx (7) print (Te St.getx ())

Python black Magic Collection

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.