>>> class C(object): ... def __init__(self, s): ... print s ... >>> myclass = C >>> type(C) <type 'type'> >>> type(myclass) <type 'type'> >>> myclass(2) 2 <__main__.C object at 0x10e2bea50> >>> map(myclass, [1,2,3]) 1 2 3 [<__main__.C object at 0x10e2be9d0>, <__main__.C object at 0x10e2bead0>, <__main__.C object at 0x10e2beb10>] >>> map(C, [1,2,3]) 1 2 3 [<__main__.C object at 0x10e2be950>, <__main__.C object at 0x10e2beb50>, <__main__.C object at 0x10e2beb90>] >>> C.test_attribute = True >>> myclass.test_attribute True
>>> def make_class(class_name): ... class C(object): ... def print_class_name(self): ... print class_name ... C.__name__ = class_name ... return C ... >>> C1, C2 = map(make_class, ["C1", "C2"]) >>> c1, c2 = C1(), C2() >>> c1.print_class_name() C1 >>> c2.print_class_name() C2 >>> type(c1) <class '__main__.C1'> >>> type(c2) <class '__main__.C2'> >>> c1.print_class_name.__closure__ (<cell at 0x10ab6dbe8: str object at 0x10ab71530>,)
>>> MyClass = type("MyClass", (object,), {"my_attribute": 0})
>>> type(MyClass)
<type 'type'>
>>> o = MyClass()
>>> o.my_attribute
0
>>> def myclass_init(self, my_attr):
... self.my_attribute = my_attr
...
>>> MyClass = type("MyClass", (object,), {"my_attribute": 0, "__init__": myclass_init})
>>> o = MyClass("Test")
>>> o.my_attribute
'Test'
>>> o.__init__
<bound method MyClass.myclass_init of <__main__.MyClass object at 0x10ab72150>>
>>> def mymetaclass(name, parents, attributes): ... return "Hello" ... >>> class C(object): ... __metaclass__ = mymetaclass ... >>> print C Hello >>> type(C) <type 'str'>
def log_everything_metaclass(class_name, parents, attributes):
print "Creating class", class_name
myattributes = {}
for name, attr in attributes.items():
myattributes[name] = attr
if hasattr(attr, '__call__'):
myattributes[name] = logged("%b %d %Y - %H:%M:%S",
class_name + ".")(attr)
return type(class_name, parents, myattributes)
class C(object):
__metaclass__ = log_everything_metaclass
def __init__(self, x):
self.x = x
def print_x(self):
print self.x
# Usage:
print "Starting object creation"
c = C("Test")
c.print_x()
# Output:
Creating class C
Starting object creation
- Running 'C.__init__' on Aug 05 2013 - 13:50:58
- Finished 'C.__init__', execution time = 0.000s
- Running 'C.print_x' on Aug 05 2013 - 13:50:58
Test
- Finished 'C.print_x', execution time = 0.000s
def my_metaclass(class_name, parents, attributes):
print "In metaclass, creating the class."
return type(class_name, parents, attributes)
def my_class_decorator(class_):
print "In decorator, chance to modify the class."
return class_
@my_class_decorator
class C(object):
__metaclass__ = my_metaclass
def __init__(self):
print "Creating object."
c = C()
# Output:
In metaclass, creating the class.
In decorator, chance to modify the class.
Creating object.
frametype_class_dict = {}
class ID3v2FrameClassFactory(object):
def __new__(cls, class_name, parents, attributes):
print "Creating class", class_name
# Here we could add some helper methods or attributes to c
c = type(class_name, parents, attributes)
if attributes['frame_identifier']:
frametype_class_dict[attributes['frame_identifier']] = c
return c
@staticmethod
def get_class_from_frame_identifier(frame_identifier):
return frametype_class_dict.get(frame_identifier)
class ID3v2Frame(object):
frame_identifier = None
__metaclass__ = ID3v2FrameClassFactory
pass
class ID3v2TitleFrame(ID3v2Frame):
__metaclass__ = ID3v2FrameClassFactory
frame_identifier = "TIT2"
class ID3v2CommentFrame(ID3v2Frame):
__metaclass__ = ID3v2FrameClassFactory
frame_identifier = "COMM"
title_class = ID3v2FrameClassFactory.get_class_from_frame_identifier('TIT2')
comment_class = ID3v2FrameClassFactory.get_class_from_frame_identifier('COMM')
print title_class
print comment_class
# Output:
Creating class ID3v2Frame
Creating class ID3v2TitleFrame
Creating class ID3v2CommentFrame
<class '__main__.ID3v2TitleFrame'>
<class '__main__.ID3v2CommentFrame'>
frametype_class_dict = {}
class ID3v2FrameClass(object):
def __init__(self, frame_id):
self.frame_id = frame_id
def __call__(self, cls):
print "Decorating class", cls.__name__
# Here we could add some helper methods or attributes to c
if self.frame_id:
frametype_class_dict[self.frame_id] = cls
return cls
@staticmethod
def get_class_from_frame_identifier(frame_identifier):
return frametype_class_dict.get(frame_identifier)
@ID3v2FrameClass(None)
class ID3v2Frame(object):
pass
@ID3v2FrameClass("TIT2")
class ID3v2TitleFrame(ID3v2Frame):
pass
@ID3v2FrameClass("COMM")
class ID3v2CommentFrame(ID3v2Frame):
pass
title_class = ID3v2FrameClass.get_class_from_frame_identifier('TIT2')
comment_class = ID3v2FrameClass.get_class_from_frame_identifier('COMM')
print title_class
print comment_class
Decorating class ID3v2Frame
Decorating class ID3v2TitleFrame
Decorating class ID3v2CommentFrame
<class '__main__.ID3v2TitleFrame'>
<class '__main__.ID3v2CommentFrame'>
>>> def mydecorator(cls): ... cls.__doc__ = "Test!" ... return cls ... >>> @mydecorator ... class C(object): ... """Docstring to be replaced with Test!""" ... pass ... Traceback (most recent call last): File "<stdin>", line 2, in <module> File "<stdin>", line 2, in mydecorator AttributeError: attribute '__doc__' of 'type' objects is not writable >>> def mymetaclass(cls, parents, attrs): ... attrs['__doc__'] = 'Test!' ... return type(cls, parents, attrs) ... >>> class D(object): ... """Docstring to be replaced with Test!""" ... __metaclass__ = mymetaclass ... >>> D.__doc__ 'Test!'
>>> class meta(type): ... def __new__(cls, class_name, parents, attributes): ... print "meta.__new__" ... return super(meta, cls).__new__(cls, class_name, parents, attributes) ... def __call__(self, *args, **kwargs): ... print "meta.__call__" ... return super(meta, self).__call__(*args, **kwargs) ... >>> class C(object): ... __metaclass__ = meta ... meta.__new__ >>> c = C() meta.__call__ >>> type(C) <class '__main__.meta'>
class my_metaclass(type):
def __new__(cls, class_name, parents, attributes):
print "- my_metaclass.__new__ - Creating class instance of type", cls
return super(my_metaclass, cls).__new__(cls,
class_name,
parents,
attributes)
def __init__(self, class_name, parents, attributes):
print "- my_metaclass.__init__ - Initializing the class instance", self
super(my_metaclass, self).__init__(self)
def __call__(self, *args, **kwargs):
print "- my_metaclass.__call__ - Creating object of type ", self
return super(my_metaclass, self).__call__(*args, **kwargs)
def my_class_decorator(cls):
print "- my_class_decorator - Chance to modify the class", cls
return cls
@my_class_decorator
class C(object):
__metaclass__ = my_metaclass
def __new__(cls):
print "- C.__new__ - Creating object."
return super(C, cls).__new__(cls)
def __init__(self):
print "- C.__init__ - Initializing object."
c = C()
print "Object c =", c
- my_metaclass.__new__ - Creating class instance of type <class '__main__.my_metaclass'> - my_metaclass.__init__ - Initializing the class instance <class '__main__.C'> - my_class_decorator - Chance to modify the class <class '__main__.C'> - my_metaclass.__call__ - Creating object of type <class '__main__.C'> - C.__new__ - Creating object. - C.__init__ - Initializing object. Object c = <__main__.C object at 0x1043feb90> <class '__main__.C'>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有