# 创建工厂类函数
def create_animal_class():
def init(self,name):
self.name = name
def eat(self):
pass
def go_to_vet(self):
pass
return type('Animal',(object,),{
'__doc__': "a class representing an animal", '__init__': init,
'eat': eat, 'go_to_vet': go_to_vet
})
animal1 = create_animal_class()
animal2 = create_animal_class()
print(animal1 == animal2)
def creat_animal_classes():
class Animal(object):
def __init__(self, name):
self.name = name
def eat(self):
pass
def go_to_vet(self):
pass
return Animal
class C(object):
foo = 'bar'
@classmethod
def classfoo(cls):
return cls.foo
#关于单例模式(让类工厂返回类的实例,而不是返回类)
def CPrime(new_foo='bar'):
if new_foo == 'bar':
return C()
class SubC(C):
foo = new_foo
return SubC()
cprime = CPrime('foo')
print(cprime)
cprime = CPrime('foo1')
print(cprime)
# 上述方式存在的问题:很多类需要将参数发送给__init__方法,此时该函式就无法处理这种情况
import csv
from django import forms
def CredentialForm(service,*args,**kwargs):
"返回类实例"
keys = []
with open('creds.csv','r') as csvfile:
for row in csv.reader(csvfile):
if row[0].lower() != service.lower():
continue
keys.append(row[1])
attrs = {}
for key in keys:
field_kw = {}
if key == 'password':
field_kw['widget'] = forms.PasswordInput
attrs[key] = forms.CharField(**field_kw)
metaclass = type(forms.Form)
cls = metaclass('CredentialForm',(forms.Form,),attrs)
return cls(*args,**kwargs)