用模块、框架实现业务功能,作为扩展的知识点。
创建类

  1. # 定义类
  2. class Foo(object):
  3. def __init__(self, name):
  4. self.name = name
  5. def __new__(cls, *args, **kwargs):
  6. return object.__new__(cls)
  7. # 根据类创建对象
  8. # 1 执行类的new方法,创建空对象 【构造方法】 {}
  9. # 2 执行类的init方法,初始化对象 【初始化方法】{name:"luffy"}
  10. obj = Foo("luffy")

对象是基础类创建的。
问题:类是谁创建的?
答案:类是由type创建。

  1. # 传统方式创建类
  2. class Foo(object):
  3. v1 = 123
  4. def func(self):
  5. return 666
  6. # 非传统方式创建类
  7. Foo = type("Foo", (object,),{"v1": 123, "func":lambda self:666})
  8. # 非传统方式创建对象
  9. obj = Foo()
  10. # 非传统方式调用v1的变量
  11. print(obj.v1)
  1. # 传统方式创建类(直观)
  2. """
  3. class Foo(object):
  4. v1 = 123
  5. def func(self):
  6. return 666
  7. print(Foo)
  8. """
  9. # 非传统方式(一行)
  10. # 1 创建类型
  11. # - 类名
  12. # - 继承类
  13. # - 成员
  14. Fa = type("Foo", (object,), {"v1":123, "func": lambda self:666, "do":do})
  15. # 2 根据类创建对象
  16. obj = Fa()
  17. # 3 调用对象中的v1变量
  18. print(obj.v1)
  19. # 4 执行对象中的func方法
  20. result = obj.func()

类默认是以type创建,怎么让伊特类的创建改成其他的东西(元类)。

  1. # type 创建Foo类
  2. class Foo(object):
  3. pass
  4. # 其他的东西创建类
  5. class Foo(object, metaclass=其他的东西)
  6. pass
  1. class MyType(type):
  2. pass
  3. class Foo(object, metaclass=MyType):
  4. pass
  5. # Foo类由MyType创建
  1. class MyType(type):
  2. def __init__(self, *args, **kwargs):
  3. super().__init__(*args, **kwargs)
  4. def __new__(cls, *args, **kwargs):
  5. new_cls = super().__new__(cls, *args, **kwargs)
  6. return new_cls
  7. def __call__(self, *args, **kwargs):
  8. # 调用自己的那个类 __new__ 方法去创建对象
  9. empty_object = self.__new__(self)
  10. # 调用你自己的__init__ 方法取初始化
  11. self.__init__(empty_object, *args, **kwargs)
  12. return empty_object
  13. class Foo(object, metaclass=MyType):
  14. def __init__(self, name):
  15. self.name = name
  16. # 假设Foo是一个对象 由MyType创建
  17. # Foo其实是MyType的一个对象
  18. # Foo() -> MyType对象()
  19. v1 = Foo("alex")
  20. print(v1)
  21. print(v1.name)

wtforms源码

  1. from wtforms import Form
  2. from wtforms.fields import simple
  3. class LoginForm(Form) :
  4. name = simple.StringField(label='用户名', render_kw={'class': 'form-control'})
  5. pwd = simple.PasswordField(label= '密码', render_kw={'class':'form-control'})
  6. form = LoginForm( )
  7. print(form.name) #类变量
  8. print(form.pwd) #类变量
  1. from wtforms import Form
  2. from wtforms.fields import simple
  3. class FormMeta(type):
  4. def __init__(cls, name, bases, attrs):
  5. type.__init__(cls, name, bases, attrs)
  6. cls._unbound_fields = None
  7. cls._Wtforms_meta = None
  8. def __call__(cls, *args, **kwargs):
  9. """
  10. Construct a new Form instance .
  11. Creates the unbound_ fields list and the internal wtforms_ meta
  12. subclass of the class Meta in order to allow a proper inher itance
  13. hierarchy.
  14. """
  15. if cls._unbound_fields is None:
  16. fields = []
  17. for name in dir(cls):
  18. if not name.startswith('_'):
  19. unbound_field = getattr(cls, name)
  20. if hasattr (unbound_field, '_formfield'):
  21. fields. append( (name, unbound_field))
  22. # We keep the name as the. second element of the sort
  23. # to ensure a stable sort.
  24. fields .sort (key=lambda x:(x[1].creation_ounter, x[0]))
  25. cls._unbound_fields = fields
  26. # Create a subclass of the 'class Meta' using all the ancestors .
  27. if cls._wtforms_meta is None:
  28. bases=[]
  29. for mro_class in cls.__mro__:
  30. if 'Meta' in mro_class.__dict__:
  31. bases.append(mro_class.Meta)
  32. cls._wtforms_meta = type('Meta' , tuple(bases), {})
  33. return type.__call__(cls, *args, **kwargs)
  34. def with_metaclass(meta, base=object):
  35. # FormMeta("NewBase". (BaseForm,), {} )
  36. # type( "NewBase", ( BaseForm,), {} )
  37. return meta("NewBase", (base,), {})
  38. """
  39. class NewBase ( BaseForm, metaclass=FormMeta):
  40. pass
  41. class Form( NewBase):
  42. """
  43. class Form(with_metaclass(FormMeta, BaseForm)):
  44. pass
  45. # LoginForm其实是由FormMeta 创建的。
  46. # 1.创建类时,会执行FormMeta 的__new__ 和__init__,内部在类中添加了两个类变量 _unbound_fields 和_wtforms_meta
  47. class LoginForm(Form):
  48. name = simple.StringField(label='用户名', render_kw={'class': ' form-control' })
  49. pwd = simple.PasswordField(labe1='密码', render_kw={'class': 'form-control'})
  50. # 2.根据LoginForm类去创建对象。FormMeta._ call___ 方法 -> LoginForm中的new去创建对象,init去初始化对象。
  51. form = LoginForm( )
  52. print( form.name) # 类变量
  53. print(form.pwd) # 类变量
  54. # 问题1:此时LoginForm是由 type or FormMeta创建?
  55. """
  56. 类中metaclass,自己类由于metaclass定义的类来创建。
  57. 类继承某个类,父类metaclass, 自己类由于metaclass定义的类来创建。
  58. """

在学习元类之后,在:

  • 类创建,自定义功能
  • 对象的创建前后,自定义功能

    单例模式

    元类的方式 ```python class MyType(type): def init(self, name, bases, attrs):

    1. super().__init__(name, bases, attrs)
    2. self.instance = None

    def call(self, args, *kwargs):

    1. # 1判断是否有对象, 有不穿件
    2. if not self.instance:
    3. self.__init__(self.instance, *args, **kwargs)
    4. return self.instance

class Singleton(object, metaclass=MyType): pass

class Foo1(Singleton, metaclass=MyType): pass

class Foo2(Singleton): pass

v1 = Foo1() v2 = Foo1()

print(v1) print(v2) ```