• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python new.instance函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中new.instance函数的典型用法代码示例。如果您正苦于以下问题:Python instance函数的具体用法?Python instance怎么用?Python instance使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了instance函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: rule

    def rule(self):
        if self.subNodes is not None:
            extension = new.instance(pmml.Extension)
            extension.tag = "Extension"
            extension.attrib = {"name": "gain", "value": self.bestGain}
            extension.children = []

            output = new.instance(pmml.CompoundRule)
            output.tag = "CompoundRule"
            output.attrib = {}
            output.children = [extension, self.pmmlTrue]
            output.predicateIndex = 1

            for subNode, var, cat, val in zip(self.subNodes, self.cutVar, self.cutCat, self.cutVal):
                node = subNode.rule()

                predicate = new.instance(pmml.SimplePredicate)
                predicate.tag = "SimplePredicate"
                if val is None:
                    predicate.attrib = {"field": var, "operator": "equal", "value": cat}
                else:
                    predicate.attrib = {"field": var, "operator": "greaterThan" if cat else "lessOrEqual", "value": val}
                predicate.children = []

                node[node.predicateIndex] = predicate

                output.children.append(node)
        else:
            output = new.instance(pmml.SimpleRule)
            output.tag = "SimpleRule"
            output.attrib = {"score": self.score}
            output.children = [self.pmmlTrue]
            output.predicateIndex = 0

        return output
开发者ID:Huskyeder,项目名称:augustus,代码行数:35,代码来源:trees.py


示例2: _unjelly_instance

 def _unjelly_instance(self, rest):
     clz = self.unjelly(rest[0])
     if type(clz) is not types.ClassType:
         raise InsecureJelly("Instance found with non-class class.")
     if hasattr(clz, "__setstate__"):
         inst = instance(clz, {})
         state = self.unjelly(rest[1])
         inst.__setstate__(state)
     else:
         state = self.unjelly(rest[1])
         inst = instance(clz, state)
     if hasattr(clz, 'postUnjelly'):
         self.postCallbacks.append(inst.postUnjelly)
     return inst
开发者ID:fxia22,项目名称:ASM_xf,代码行数:14,代码来源:jelly.py


示例3: get_class

 def get_class(kls, attrs):
     parts = __name__.split('.')
     module = "%s.%s" % (".".join(parts[:-1]), kls)
     m = importlib.import_module(module)
     m = getattr(m, kls.title())
     m = new.instance(m, attrs)
     return m            
开发者ID:rkrysinski,项目名称:gae-python-example,代码行数:7,代码来源:dispatcher.py


示例4: _simplePredicate

 def _simplePredicate(self, field, value, operator):
     p = new.instance(pmml.SimplePredicate)
     p.tag = "SimplePredicate"
     p.children = []
     p.attrib = dict(field=field, value=value, operator=operator)
     p.post_validate()
     return p
开发者ID:Huskyeder,项目名称:augustus,代码行数:7,代码来源:segmentationschema.py


示例5: evaluate

    def evaluate(self):
        classe = _RpcUtils.class_for_name(self.serviceIntfName)

        if self.serviceMethodName not in classe.__dict__:
            raise _RpcException(__err_msg__["met.nf"] % (self.serviceIntfName, self.serviceMethodName))

        serialization = {}
        methods = []

        _RpcUtils.multi_inherit_serialization(classe, serialization, methods)

        if len(serialization) > 0:
            if self.serviceMethodName in serialization:
                self.returnType = serialization[self.serviceMethodName]
            else:
                raise _RpcException(__err_msg__["ser.met.nf"] % (self.serviceIntfName, self.serviceMethodName))
        else:
            raise _RpcException(__err_msg__["ser.nf"] % (self.serviceIntfName))

        instance = new.instance(classe)
        method = getattr(instance, self.serviceMethodName)

        RpcHandler.ctx.serviceInstance = instance
        RpcHandler.ctx.methodInstance = method

        RpcHandler._callInterceptors("beforeEvaluate")
        val = method.__call__(*self.parameterValues)
        RpcHandler.ctx.responseObject = val
        RpcHandler._callInterceptors("afterEvaluate")

        return val
开发者ID:unknown-jin-c,项目名称:PGR,代码行数:31,代码来源:core.py


示例6: __new

 def __new(cls, C):
     try:
         import new
         return new.instance(C)
     except:
         pass
     return Exception.__new__(C)
开发者ID:splice,项目名称:gofer,代码行数:7,代码来源:dispatcher.py


示例7: __deepcopy__

 def __deepcopy__(self, memo={}):
     output = new.instance(self.__class__)
     output.__dict__ = copy.deepcopy(self.__dict__, memo)
     if "repr" in output.__dict__:
         del output.__dict__["repr"]
     memo[id(self)] = output
     return output
开发者ID:ReallyNiceGuy,项目名称:svgfig,代码行数:7,代码来源:svg.py


示例8: falseSimplePredicate

 def falseSimplePredicate(self):
     output = new.instance(pmml.SimplePredicate)
     output.tag = "SimplePredicate"
     output.attrib = {"field": self.name, "operator": "lessOrEqual", "value": self.value}
     output.children = []
     output.needsValue = False
     return output
开发者ID:Huskyeder,项目名称:augustus,代码行数:7,代码来源:trees.py


示例9: __copy__

 def __copy__(self):
     obj = new.instance(self.__class__, self.__dict__)
     obj.distutils_vars = obj.distutils_vars.clone(obj._environment_hook)
     obj.command_vars = obj.command_vars.clone(obj._environment_hook)
     obj.flag_vars = obj.flag_vars.clone(obj._environment_hook)
     obj.executables = obj.executables.copy()
     return obj
开发者ID:8848,项目名称:Pymol-script-repo,代码行数:7,代码来源:__init__.py


示例10: getNewInstance

def getNewInstance(fullClassName, searchPath=['./']):
    """@return: an instance of the fullClassName class WITHOUT the C{__init__} method having been called"""

    # Was original, then modified with parts of
    # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/223972

    parts = fullClassName.split('.')
    className = parts.pop()
    moduleName = parts.pop()
    package = '.'.join(parts)

    try:
        module = sys.modules[package + '.' + moduleName]
    except KeyError:
        if len(parts) > 0:
            module = __import__(package + "." + moduleName, globals(), locals(), [''])
        else:
            module = __import__(moduleName, globals(), locals())

    function = getattr(module, className)

    if not callable(function):
        raise ImportError(fullFuncError)

    return new.instance(function)
开发者ID:dagvl,项目名称:commitmessage,代码行数:25,代码来源:util.py


示例11: load

 def load(cls, filename):
     f = open(filename)
     data = cPickle.load(f)
     f.close()
     obj = new.instance(cls, data)
     obj.verbose = False
     return obj
开发者ID:auag92,项目名称:n2dm,代码行数:7,代码来源:rdf.py


示例12: _new

    def _new(S, name, args, kwargs):
        # can only call _new if we have a matching class to instantiate
        if not S._class: raise RuntimeError, "instances of this type not available"

        # check that it isn't already there!
        try:
            getinst(S._path, name)
            raise RuntimeError, "tried to create an instance that already exists"
        except NoSuchObject: pass  # we *expect* this
        
        # construct the new object. Do *not* call __init__ yet!
        newobj = new.instance(S._class, {})

        # Call Object.__setup__ to do required object setup, eg. set object
        # name.
        fullname = S._path + '%' + name
        Object.__setup__(newobj, fullname, name)

        # Call the real __init__ if it's there
        if hasattr(newobj, '__init__'):
            apply(newobj.__init__, args, kwargs)

        # Remember to cache the new instance!
        ocache[fullname] = newobj
        return newobj
开发者ID:ap0ught,项目名称:16k-mudd,代码行数:25,代码来源:db.py


示例13: recv_packet

	def recv_packet(self, block=True):
		buf = self.recv_buf
		packet = self.recv_pkt
		while True:
			if self.recv_ready():
				break
			if packet.parse(buf) == -1:
				return -1

			# TODO: callbacks
			if packet.event == packet.EVENT_NONE:
				if block:
					self.net_recv()
				else:
					return None
			elif packet.event == packet.EVENT_READY:
				#print 'body ready'
				pass
			elif packet.event == packet.EVENT_CHUNK:
				#print 'chunk', repr(packet.chunk_body)
				packet.body += packet.chunk_body
			elif packet.event == packet.EVENT_HEAD:
				#print 'head ready'
				pass

		if packet.get_header('Connection').lower() == 'keep-alive':
			#print 'keep-alive'
			self.keep_alive = True
		else:
			#print 'not keep-alive'
			self.keep_alive = False

		self.recv_pkt = new.instance(self.recv_pkt.__class__)
		self.recv_pkt.__init__()
		return packet
开发者ID:aviatorBeijing,项目名称:ptpy,代码行数:35,代码来源:http_link.py


示例14: getRandomStruct

def getRandomStruct(typeCode, compRef):
    '''
    Helper function
    '''
    structDef = getDefinition(typeCode.id())
        
    try:
        return getKnownBaciType(structDef._get_id())
    except:
        pass
    
    #determine which namespace the struct is in...
    #changes 'IDL:alma/someMod/.../struct:1.0" to 
    # [ 'someMod', ...,'struct' ]
    nameHierarchy = structDef._get_id().split(':')[1].split('/')[1:]
    #Just the 'struct' part...
    structName = nameHierarchy.pop()
    moduleName = nameHierarchy.pop(0)
    LOGGER.logTrace("module=" + moduleName
                        + "; hierarchy=" + str(nameHierarchy)
                        + "; struct="    + structName)        
    #import the top module
    tGlobals = {}
    tLocals = {}
    #module object where the struct is contained
    container = __import__(moduleName, tGlobals, tLocals, [])
    if container == None:
        msg =  "import of module \'" + moduleName + "\' failed"
        LOGGER.logCritical(msg)
        raise CORBA.NO_IMPLEMENT(msg) 
                 
    # Now navigate down the nested hierarchy of objects
    for h in nameHierarchy:
        previousContainer = container
        container = container.__dict__.get(h) 
        if container == None:
            msg =  "Name \'" + h + "\' not found in " + str( previousContainer)
            LOGGER.logCritical(msg)
            raise CORBA.NO_IMPLEMENT(msg)                   
   
    #class object for the struct
    tClass = container.__dict__.get(structName)
    if tClass == None:
        msg =  "Could not get structure \'" + structName + "\' from " \
                    + str(container)
        LOGGER.logCritical(msg)
        raise CORBA.NO_IMPLEMENT(msg) 

    #create an instance of the struct using a kooky Python mechanism.
    retVal = instance(tClass)

    #populate the fields of the struct using the IFR
    for member in structDef._get_members():
        LOGGER.logTrace("Adding a member variable for: " + 
                         str(member.name))
        retVal.__dict__[member.name] = getRandomValue(member.type_def._get_type(), 
                                                      compRef)
    
    return retVal
开发者ID:franciscobeltran,项目名称:ACS,代码行数:59,代码来源:Generator.py


示例15: accept

	def accept(self):
		sock, addr = self.sock.accept()
		link = new.instance(self.__class__)
		link.__init__(sock)
		link.role = LINK_ROLE_ACCEPT
		link.parent = self
		link.remote_addr = "%s:%d" % sock.getpeername()
		return link
开发者ID:aviatorBeijing,项目名称:ptpy,代码行数:8,代码来源:link_base.py


示例16: makeClass

def makeClass(module, classname, dict):
    exec('import %s' % (module))
    klass = eval('%s.%s' % (module, classname))
    obj = new.instance(klass) 
    if hasMethod(obj, 'from_yaml'):
        return obj.from_yaml(dict)
    obj.__dict__ = dict
    return obj
开发者ID:Alwnikrotikz,项目名称:phoenix-itorrent,代码行数:8,代码来源:klass.py


示例17: unjelly

 def unjelly(self, obj):
     if type(obj) is not types.ListType:
         return obj
     jelType = obj[0]
     if not self.taster.isTypeAllowed(jelType):
         raise InsecureJelly(jelType)
     regClass = unjellyableRegistry.get(jelType)
     if regClass is not None:
         if isinstance(regClass, ClassType):
             inst = _Dummy() # XXX chomp, chomp
             inst.__class__ = regClass
             method = inst.unjellyFor
         else:
             method = regClass # this is how it ought to be done
         val = method(self, obj)
         if hasattr(val, 'postUnjelly'):
             self.postCallbacks.append(inst.postUnjelly)
         return val
     regFactory = unjellyableFactoryRegistry.get(jelType)
     if regFactory is not None:
         state = self.unjelly(obj[1])
         inst = regFactory(state)
         if hasattr(inst, 'postUnjelly'):
             self.postCallbacks.append(inst.postUnjelly)
         return inst
     thunk = getattr(self, '_unjelly_%s'%jelType, None)
     if thunk is not None:
         ret = thunk(obj[1:])
     else:
         nameSplit = string.split(jelType, '.')
         modName = string.join(nameSplit[:-1], '.')
         if not self.taster.isModuleAllowed(modName):
             raise InsecureJelly("Module %s not allowed (in type %s)." % (modName, jelType))
         clz = namedObject(jelType)
         if not self.taster.isClassAllowed(clz):
             raise InsecureJelly("Class %s not allowed." % jelType)
         if hasattr(clz, "__setstate__"):
             ret = instance(clz, {})
             state = self.unjelly(obj[1])
             ret.__setstate__(state)
         else:
             state = self.unjelly(obj[1])
             ret = instance(clz, state)
         if hasattr(clz, 'postUnjelly'):
             self.postCallbacks.append(ret.postUnjelly)
     return ret
开发者ID:fxia22,项目名称:ASM_xf,代码行数:46,代码来源:jelly.py


示例18: bestTree

    def bestTree(self, parent, bestClassification, producer):
        if self.split is None:
            pmmlTrue = new.instance(pmml.pmmlTrue)
            pmmlTrue.tag = "True"
            pmmlTrue.attrib = {}
            pmmlTrue.children = []

            trueNode = new.instance(pmml.Node)
            trueNode.tag = "Node"
            trueNode.attrib = {"score": bestClassification}
            trueNode.children = [pmmlTrue]
            trueNode.test = pmmlTrue.createTest()

            parent[producer.nodeIndex] = trueNode

            if len(self.true_outworlds) > 0:
                # find the single best world using max (not sorting!)
                max(self.true_outworlds.values(), key=lambda x: x.split.gainCache).bestTree(
                    trueNode, bestClassification, producer
                )

        else:
            trueNode = new.instance(pmml.Node)
            trueNode.tag = "Node"
            trueNode.attrib = {"score": self.split.score(True)}
            trueNode.children = [self.split.trueSimplePredicate()]
            trueNode.test = trueNode.children[0].createTest()

            falseNode = new.instance(pmml.Node)
            falseNode.tag = "Node"
            falseNode.attrib = {"score": self.split.score(False)}
            falseNode.children = [self.split.falseSimplePredicate()]
            falseNode.test = falseNode.children[0].createTest()

            parent.children.append(trueNode)
            parent.children.append(falseNode)

            if len(self.true_outworlds) > 0 and len(self.false_outworlds) > 0:
                # find the single best world using max (not sorting!)
                max(self.true_outworlds.values(), key=lambda x: x.split.gainCache).bestTree(
                    trueNode, bestClassification, producer
                )
                max(self.false_outworlds.values(), key=lambda x: x.split.gainCache).bestTree(
                    falseNode, bestClassification, producer
                )
开发者ID:justinrichie,项目名称:augustus,代码行数:45,代码来源:trees.py


示例19: instance

def instance(klass, d):
    if isinstance(klass, types.ClassType):
        return new.instance(klass, d)
    elif isinstance(klass, type):
        o = object.__new__(klass)
        o.__dict__ = d
        return o
    else:
        raise TypeError, "%s is not a class" % klass
开发者ID:adozenlines,项目名称:freevo1,代码行数:9,代码来源:marmalade.py


示例20: getReduced

 def getReduced(self):
     """ Returns an object of my own class, containing reduced
     versions of myself and the auxiliary criterion parts. """
     rdatapart=self.datapart.getReduced()
     rauxobjects=[o.getReduced(datapart=rdatapart) for o in self.auxobjects ]
     r=new.instance(self.__class__,{})
     r.datapart=rdatapart
     r.auxobjects=rauxobjects
     return r
开发者ID:jhkoivis,项目名称:stdic,代码行数:9,代码来源:bigfelreg.py



注:本文中的new.instance函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python new.instancemethod函数代码示例发布时间:2022-05-27
下一篇:
Python new.function函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap