本文整理汇总了Python中new.classobj函数的典型用法代码示例。如果您正苦于以下问题:Python classobj函数的具体用法?Python classobj怎么用?Python classobj使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了classobj函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: GenClass_new_class
def GenClass_new_class(attributes, myglobals):
classname = attributes[SELF][NAME]
if attributes[SELF][TYPE] != LIST:
raise AttributeError
if ANONYMOUS in attributes[SELF][FLAGS]:
listtype = GenClassAList
attributes[SELF]['install_func'] = GenClassAList_get_install_funcs
else:
listtype = GenClassList
attributes[SELF]['install_func'] = GenClassList_get_install_funcs
def GenClass_init_func(self, list=None, parent=None):
if hasattr(self.__class__, "_ListClass"):
self.__class__._ListClass.__init__(self, list, parent)
def GenClass_newClass_func(self, classname, list=None, parent=None):
klass = self.__class__._Globals[classname]
if klass:
return klass(list, parent)
else: return None
newclass = new.classobj(classname + '_base', (listtype,),
{'Attributes' : attributes,
'__init__' : GenClass_init_func,
'_ListClass' : listtype,
'_Globals' : myglobals,
'newClass' : GenClass_newClass_func})
_install_funcs(newclass)
implclass = new.classobj(classname, (newclass,),
{})
return (newclass, implclass)
开发者ID:redoop,项目名称:installer-redoop,代码行数:35,代码来源:genClass.py
示例2: __init__
def __init__(self, element):
self.__element = element
self.__tags = {}
for child in element.getchildren():
ns, tag = denamespace(child.tag)
if tag in self.__tags:
self.__tags[tag].append(child)
else:
self.__tags[tag] = child
if hasattr(self, tag):
spot = getattr(self, tag)
if type(spot) != list:
spot = [spot]
#spot.append(objectify(child))
if len(child.getchildren()):
spot.append(
new.classobj(tag, (ElementWrapper, ), {})(child))
else:
spot.append(child.text)
setattr(self, tag, spot)
setattr(self, '__islist__', True)
elif len(child.getchildren()):
setattr(self, tag,
new.classobj(tag, (ElementWrapper, ), {})(child))
else:
# marshall the type here!
setattr(self, denamespace(child.tag)[1], child.text)
开发者ID:Manduka,项目名称:soaplib,代码行数:27,代码来源:easy_client.py
示例3: loadINIPackage
def loadINIPackage(self, inifile):
"""
Load INI file containing macro definitions
Arguments:
inifile -- filename of INI formatted file
"""
ini = ConfigParser.RawConfigParser()
if not isinstance(inifile, (list,tuple)):
inifile = [inifile]
for f in inifile:
ini.read(f)
macros = {}
for section in ini.sections():
try: baseclass = self[section]
except KeyError:
log.warning('Could not find macro %s' % section)
continue
for name in ini.options(section):
value = ini.get(section,name)
m = re.match(r'^unicode\(\s*(?:(\'|\")(?P<string>.+)(?:\1)|(?P<number>\d+))\s*\)$',value)
if m:
data = m.groupdict()
if data['number'] is not None:
value = unichr(int(data['number']))
else:
value = unicode(data['string'])
macros[name] = new.classobj(name, (baseclass,),
{'unicode': value})
continue
macros[name] = new.classobj(name, (baseclass,),
{'args': value})
self.importMacros(macros)
开发者ID:EHCliffe,项目名称:plastex,代码行数:34,代码来源:Context.py
示例4: _preferences_pages_default
def _preferences_pages_default(self):
from apptools.help.help_plugin.preferences_pages import \
DocumentsPreferencesPage, DemosPreferencesPage, \
ExamplesPreferencesPage, HelpDocPreferencesPage, \
HelpDemoPreferencesPage, HelpExamplePreferencesPage
pages = []
if len(self.help_docs) > 0:
pages.append(DocumentsPreferencesPage)
pages.extend(
[ new.classobj(doc.preferences_path + 'PreferencesPage',
(HelpDocPreferencesPage,),
{'preferences_path': doc.preferences_path},
) for doc in self.help_docs
])
if len(self.help_demos) > 0:
pages.append(DemosPreferencesPage)
pages.extend(
[ new.classobj(demo.preferences_path + 'PreferencesPage',
(HelpDemoPreferencesPage,),
{'preferences_path': demo.preferences_path},
) for demo in self.help_demos
])
if len(self.help_examples) > 0:
pages.append(ExamplesPreferencesPage)
pages.extend(
[ new.classobj(example.preferences_path + 'PreferencesPage',
(HelpExamplePreferencesPage,),
{'preferences_path': example.preferences_path},
) for example in self.help_examples
])
return pages
开发者ID:archcidburnziso,项目名称:apptools,代码行数:31,代码来源:help_plugin.py
示例5: __init__
def __init__(self, entity=None, base=None, **kw):
""" """
self.get_table_args()
if entity:
self._dao = entity
else:
if len(self.__slots__) == 0:
if base:
self.__decl_base = base
self._dao = \
base._decl_class_registry[self.__class__.__name__]()\
if self.__class__.__name__ in base._decl_class_registry\
else classobj(
self.__class__.__name__,
(self.__clz_proxy__,base,),
self.get_table_args() or {}
)() # instantiate
else:
self._dao = classobj(
self.__class__.__name__,
(self.__clz_proxy__,(object,),),
self.get_table_args() or {}
)() # instantiate
self.__class__.__decl_class__ = self._dao.__class__
for k,v in kw.items():
setattr(self, k, v)
if hasattr(self, 'mixin'):
if 'entity_mixes' in self.__pyaella_args__:
for em in self.__pyaella_args__['entity_mixes']:
self.mixin(em)
开发者ID:migacollabs,项目名称:Pyaella,代码行数:32,代码来源:__init__.py
示例6: suite
def suite():
suite = unittest.TestSuite()
if has_svn:
tests = [(NormalTests, ''),
(ScopedTests, u'/tête'),
(RecentPathScopedTests, u'/tête/dir1'),
(NonSelfContainedScopedTests, '/tags/v1'),
(AnotherNonSelfContainedScopedTests, '/branches'),
]
skipped = {
'SvnCachedRepositoryNormalTests': [
'test_changeset_repos_creation',
],
'SvnCachedRepositoryScopedTests': [
'test_changeset_repos_creation',
'test_rev_navigation',
],
}
for test, scope in tests:
tc = new.classobj('SubversionRepository' + test.__name__,
(SubversionRepositoryTestCase, test),
{'path': REPOS_PATH + scope})
suite.addTest(unittest.makeSuite(
tc, 'test', suiteClass=SubversionRepositoryTestSetup))
tc = new.classobj('SvnCachedRepository' + test.__name__,
(SvnCachedRepositoryTestCase, test),
{'path': REPOS_PATH + scope})
for skip in skipped.get(tc.__name__, []):
setattr(tc, skip, lambda self: None) # no skip, so we cheat...
suite.addTest(unittest.makeSuite(
tc, 'test', suiteClass=SubversionRepositoryTestSetup))
else:
print "SKIP: versioncontrol/tests/svn_fs.py (no svn bindings)"
return suite
开发者ID:wiraqutra,项目名称:photrackjp,代码行数:34,代码来源:svn_fs.py
示例7: __init__
def __init__(self):
self.host = "localhost"
self.port = 2663
self.isSessionRunning = False
self.timeline = ""
self.waitStr = None
self.waitFlag = threading.Event()
self.PlayState = -1
self.lastMessage = {}
self.lastSubtitleNum = 0
self.lastSubtitlesEnabled = False
self.lastAudioTrackNum = 0
group = self.AddGroup('Requests')
for className, scancode, descr in ttRequests:
clsAttributes = dict(name=descr, value=scancode)
cls = new.classobj(className, (stdAction,), clsAttributes)
group.AddAction(cls)
group = self.AddGroup('Commands')
for className, scancode, descr, ParamDescr in ttCommands:
clsAttributes = dict(name=descr, value=scancode)
if ParamDescr == "":
if className[0:3] == "IP_":
cls = new.classobj(className, (stdAction,), clsAttributes)
else:
cls = new.classobj(className, (wmAction,), clsAttributes)
else:
cls = new.classobj(className, (stdActionWithStringParameter,), clsAttributes)
cls.parameterDescription = ParamDescr
group.AddAction(cls)
开发者ID:garbear,项目名称:EventGhost,代码行数:31,代码来源:__init__.py
示例8: validate_on_load
def validate_on_load(cls):
for e in cls.errors:
exception = classobj(str(e.error_type), (Exception,), {})
raise exception, e.error_message
for e in cls.other_errors:
exception = classobj(str(e.error_type), (Exception,), {})
raise exception, e.error_message
开发者ID:MVReddy,项目名称:TMS,代码行数:7,代码来源:base.py
示例9: invoke
def invoke(self, tex):
self.parse(tex)
attrs = self.attributes
name = attrs['name']
counter = attrs['counter']
caption = attrs['caption']
within = attrs['within']
if not counter and not attrs['*modifier*']:
counter = name
if within:
self.ownerDocument.context.newcounter(counter,initial=0,resetby=within, format='${the%s}.${%s}' % (within, name))
else:
self.ownerDocument.context.newcounter(counter,initial=0)
deflog.debug('newtheorem %s', name)
# The nodeName key below ensure all theorem type will call the same
# rendering method, the type of theorem being retained in the thmName
# attribute
if attrs['*modifier*']:
newclass = new.classobj(str(name), (Environment,),
{'caption': caption, 'nodeName': 'thmenv', 'thmName': name,
'args': '[title]'})
else:
newclass = new.classobj(str(name), (Environment,),
{'caption': caption, 'nodeName': 'thmenv', 'thmName': name,
'counter': counter, 'args': '[title]'})
self.ownerDocument.context.addGlobal(name, newclass)
开发者ID:PatrickMassot,项目名称:plastex,代码行数:27,代码来源:Definitions.py
示例10: setup
def setup(**kwargs):
"""
A drop in replacement for distutils.core.setup which
integrates nicely with kiwi.environ
:param packagename: the name of the main package to be used when it
differs from the 'name' argument
fallback to 'name' if not provided
"""
packagename = kwargs.pop('packagename', None)
# FIXME: This is for kiwi to allow setting datadir to kiwi instead of
# kiwi-gtk when uploading to pip. Is there a better way of doing this?
_VariableExtender.packagename = packagename
def run_install(self):
domain = packagename or kwargs.get('name')
if domain:
datadir = domain if 'bdist_egg' in self.distribution.commands else None
self.data_files.extend(compile_po_files(domain, datadir=datadir))
KiwiInstallData.run(self)
# distutils uses old style classes
InstallData = new.classobj('InstallData', (KiwiInstallData,),
dict(run=run_install))
InstallLib = new.classobj('InstallLib', (KiwiInstallLib,),
dict())
cmdclass = dict(install_data=InstallData, install_lib=InstallLib,
clean=KiwiClean)
kwargs.setdefault('cmdclass', cmdclass).update(cmdclass)
DS_setup(**kwargs)
开发者ID:fuinha,项目名称:kiwi,代码行数:31,代码来源:dist.py
示例11: newif
def newif(self, name, initial=False):
"""
Create a new \\if (and accompanying) commands
This method corresponds to TeX's \\newif command.
Required Arguments:
name -- name of the 'if' command. This name should always
start with the letters 'if'.
Keyword Arguments:
initial -- initial value of the 'if' command
"""
name = str(name)
# \if already exists
if self.has_key(name):
macrolog.debug('if %s already defined', name)
return
# Generate new 'if' class
macrolog.debug('creating if %s', name)
ifclass = new.classobj(name, (plasTeX.NewIf,), {'state':initial})
self.addGlobal(name, ifclass)
# Create \iftrue macro
truename = name[2:]+'true'
newclass = new.classobj(truename, (plasTeX.IfTrue,), {'ifclass':ifclass})
self.addGlobal(truename, newclass)
# Create \iffalse macro
falsename = name[2:]+'false'
newclass = new.classobj(falsename, (plasTeX.IfFalse,), {'ifclass':ifclass})
self.addGlobal(falsename, newclass)
开发者ID:EHCliffe,项目名称:plastex,代码行数:34,代码来源:Context.py
示例12: setup
def setup(**kwargs):
"""
A drop in replacement for distutils.core.setup which
integrates nicely with kiwi.environ
:attribute resources:
:attribute global_resources:
:attribute templates: List of templates to install
"""
resources = {}
global_resources = {}
templates = []
if 'resources' in kwargs:
resources = kwargs.pop('resources')
if 'global_resources' in kwargs:
global_resources = kwargs.pop('global_resources')
if 'templates' in kwargs:
templates = kwargs.pop('templates')
def run_install(self):
name = kwargs.get('name')
if name:
self.data_files.extend(compile_po_files(name))
KiwiInstallData.run(self)
varext = _VariableExtender(self.distribution)
for path, files in templates:
# Skip templates inside eggs for now
if 'bdist_egg' in self.distribution.commands:
continue
install = self.distribution.get_command_obj('install')
target = os.path.join(install.prefix, path)
if install.root:
if target[0] == '/':
target = target[1:]
target = os.path.join(install.root, target)
if not os.path.exists(target):
info("creating %s" % target)
os.makedirs(target)
for filename in files:
data = open(filename).read()
data = varext.extend(data)
target_file = os.path.join(target, os.path.basename(filename))
info('installing template %s' % target_file)
open(target_file, 'w').write(data)
# distutils uses old style classes
InstallData = new.classobj('InstallData', (KiwiInstallData,),
dict(run=run_install))
InstallLib = new.classobj('InstallLib', (KiwiInstallLib,),
dict(resources=resources,
global_resources=global_resources))
cmdclass = dict(install_data=InstallData, install_lib=InstallLib,
clean=KiwiClean)
kwargs.setdefault('cmdclass', cmdclass).update(cmdclass)
DS_setup(**kwargs)
开发者ID:relsi,项目名称:kiwi,代码行数:59,代码来源:dist.py
示例13: newenvironment
def newenvironment(self, name, nargs=0, definition=None, opt=None):
"""
Create a \\newenvironment
Required Arguments:
name -- name of the macro to create
nargs -- integer number of arguments that the macro has
definition -- two-element tuple containing the LaTeX definition.
Each element should be a string. The first element
corresponds to the beginning of the environment, and the
second element is the end of the environment.
opt -- string containing the LaTeX code to use in the
optional argument
Examples::
c.newenvironment('mylist', 0, (r'\\begin{itemize}', r'\\end{itemize}'))
"""
name = str(name)
# Macro already exists
if self.has_key(name):
if not issubclass(self[name], (plasTeX.NewCommand,
plasTeX.Definition)):
return
macrolog.debug('redefining environment "%s"', name)
if nargs is None:
nargs = 0
assert isinstance(nargs, int), 'nargs must be an integer'
if definition is not None:
assert isinstance(definition, (tuple,list)), \
'definition must be a list or tuple'
assert len(definition) == 2, 'definition must have 2 elements'
if isinstance(definition[0], basestring):
definition[0] = [x for x in Tokenizer(definition[0], self)]
if isinstance(definition[1], basestring):
definition[1] = [x for x in Tokenizer(definition[1], self)]
if isinstance(opt, basestring):
opt = [x for x in Tokenizer(opt, self)]
macrolog.debug('creating newenvironment %s', name)
# Begin portion
newclass = new.classobj(name, (plasTeX.NewCommand,),
{'nargs':nargs,'opt':opt,'definition':definition[0]})
self.addGlobal(name, newclass)
# End portion
newclass = new.classobj('end'+name, (plasTeX.NewCommand,),
{'nargs':0,'opt':None,'definition':definition[1]})
self.addGlobal('end' + name, newclass)
开发者ID:EHCliffe,项目名称:plastex,代码行数:54,代码来源:Context.py
示例14: get_class
def get_class(self, name, inuse=False):
"""
return a ClassSerializer named name, if the class hasn't previously
been request create a new class, otherwise return the cached class.
"""
try:
klass = self.ctypes["{%s}%s" % (self.tns, name)]
except:
typeklass = new.classobj("types", (), {})
klass = new.classobj(name, (ClassSerializer, object), {"types": typeklass, "__name__": name})
self.ctypes["{%s}%s" % (self.tns, name)] = klass
if not getattr(klass, "inuse", False):
klass.inuse = inuse
return klass
开发者ID:stacktracer,项目名称:soaplib_0.8.x,代码行数:14,代码来源:typeparse.py
示例15: get_app
def get_app(config, config_vars, profiler=None, ctx_mixins=None, **kwargs):
app_bases = [HandleExceptionMixin]
if ctx_mixins:
ctx_bases = list(ctx_mixins)
else:
ctx_bases = []
if profiler:
app_bases.append(ProfilerMixin)
if config.session_server:
try:
sess_serv_host, sess_serv_port = config.session_server.split(':')
except ValueError:
sess_serv_host, sess_serv_port = config.session_server, 34343
else:
try:
sess_serv_port = int(sess_serv_port)
except ValueError:
sys.exit('bad session server port specification: %s' %
sess_serv_port)
kwargs['session_appid'] = config.appname
kwargs['session_server'] = sess_serv_host
kwargs['server_port'] = sess_serv_port
if config.session_timeout:
kwargs['session_age'] = int(config.session_timeout)
else:
kwargs['session_age'] = 600
app_bases.append(ModularSessionApp)
if have_branching_session:
ctx_bases.append(BranchingSessionContext)
else:
ctx_bases.append(SessionAppContext)
else:
app_bases.append(ModularApp)
ctx_bases.append(SimpleAppContext)
ctx_bases.append(CommonAppContext)
kwargs['secret'] = config.session_secret
# This is a *little* gross... create a class on the fly
ctx_cls = new.classobj('AlbaCtx', tuple(ctx_bases),
dict(__init__=call_all('__init__')))
def create_context(self):
return ctx_cls(self)
app_cls = new.classobj('AlbaApp', tuple(app_bases),
dict(create_context=create_context))
app = app_cls(**kwargs)
if profiler:
app.profiler = profiler
app.config = config
app.config_vars = config_vars
return app
开发者ID:timchurches,项目名称:NetEpi-Collection,代码行数:49,代码来源:albasetup.py
示例16: decorator
def decorator(base_class):
module = sys.modules[base_class.__module__].__dict__
for i, platform in enumerate(platforms):
d = dict(base_class.__dict__)
d['desired_capabilities'] = platform
name = "%s_%s" % (base_class.__name__, i + 1)
module[name] = new.classobj(name, (base_class,), d)
开发者ID:kristiansl,项目名称:Python_Parallel_demo,代码行数:7,代码来源:example.py
示例17: taskify
def taskify(baseclass, name):
smajor = baseclass._schema.version.major
sminor = baseclass._schema.version.minor
cat = baseclass._category
if cat == "applications":
schema_items = _app_schema
taskclass = TaskApplication
elif cat == "splitters":
schema_items = _splitter_schema
taskclass = TaskSplitter
classdict = {
"_schema": Schema(Version(smajor, sminor), dict(baseclass._schema.datadict.items() + schema_items)),
"_category": cat,
"_name": name,
"__init__": __task__init__,
}
if '_exportmethods' in baseclass.__dict__:
classdict['_exportmethods'] = baseclass.__dict__['_exportmethods']
cls = classobj(name, (taskclass, baseclass), classdict)
global handler_map
# Use the same handlers as for the base class
handler_map.append((getName(baseclass), name))
return cls
开发者ID:VladimirRomanovsky,项目名称:ganga,代码行数:29,代码来源:TaskApplication.py
示例18: findViewletManager
def findViewletManager(self, name):
managerObj = queryMultiAdapter((self.context, self.request, self), IViewletManager, name)
if not managerObj:
# Here's where we go totally off the deep end...
# Since we can't find this viewlet manager with the basic (self.context, self.request, self)
# multiadapter lookup, this must be some sort of custom manager, registered to other interfaces.
# In order to find it, we need to do a bit of reverse engineering...
# Since Plone's generic setup process for viewlets constrains us to one viewlet manager / name,
# we're going to assume that the adapter with this name, and a provided interface that is or extends IViewletManger
# is the one we're looking for.
# So, start with a search of the adapter registry...
reg = [reg for reg in getGlobalSiteManager().registeredAdapters() if reg.name == name][0]
# So far, I think we're stuck with context and request being the first two interfaces.
providedClasses = [self.context, self.request]
# Now, we take a look at the required interfaces...
# And create some dummy classes that implement them.
for iface in reg.required[2:]:
tempClass = classobj("dummy", (object,), {})
classImplements(tempClass, iface)
providedClasses.append(tempClass())
# Now just do a basic multiadapter lookup using our new objects providing the correct interfaces...
managerObj = queryMultiAdapter(tuple(providedClasses), reg.provided, name)
return managerObj
开发者ID:esteele,项目名称:Products.Gloworm,代码行数:28,代码来源:utils.py
示例19: _make_functions
def _make_functions(namespace):
"""Make the functions for adding modules and add them to the
namespace automatically.
"""
# Ignore these since they are already provided.
ignore = ['axes', 'text', 'orientation_axes']
for mod in registry.modules:
func_name = camel2enthought(mod.id)
class_name = mod.id
if func_name.endswith('_module'):
func_name = func_name[:-7]
class_name = class_name[:-6]
class_name = class_name + 'Factory'
# Don't create any that are already defined or ignored.
if class_name in namespace or func_name in ignore:
continue
# The class to wrap.
klass = new.classobj(class_name,
(_AutomaticModuleFactory,),
{'__doc__': mod.help,}
)
klass._metadata = mod
# The mlab helper function.
func = make_function(klass)
# Inject class/function into the namespace and __all__.
namespace[class_name] = klass
namespace[func_name] = func
__all__.append(func_name)
开发者ID:GaelVaroquaux,项目名称:mayavi,代码行数:31,代码来源:modules.py
示例20: __new__
def __new__(meta, classname, bases, classDict):
""" """
schemafp = os.path.abspath('schema.yaml')
sch = get_lexical_tokens('schema.yaml') \
if os.path.exists('schema.yaml') \
else None
if not sch:
sch = dinj.ModelConfig()
table_name_plural, table_name_standard = \
create_default_tablename(classname)
classDict['__domain__'] = sch
classDict['__schema__'] = None
classDict['__tablename__'] = table_name_plural
classDict['__pkname__'] = '%s_id'%table_name_standard
members = {
'__tablename__':table_name_plural
}
classDict['__clz_proxy__'] = classobj(classname+'Proxy', (object,), members)
return type.__new__(
meta,
classname,
(bases[0],),
classDict
)
开发者ID:migacollabs,项目名称:Pyaella,代码行数:29,代码来源:__init__.py
注:本文中的new.classobj函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论