什么是甲状腺?它们用于什么?
当前回答
型()函数可以返回对象的类型或创建一个新的类型,
例如,我们可以使用类()函数创建一个 Hi 类,并且不需要使用类 Hi(对象):
def func(self, name='mike'):
print('Hi, %s.' % name)
Hi = type('Hi', (object,), dict(hi=func))
h = Hi()
h.hi()
Hi, mike.
type(Hi)
type
type(h)
__main__.Hi
除了使用类()以动态创建类,您还可以控制类的创建行为,并使用甲塔克拉斯。
根据 Python 对象模型,类是对象,所以类必须是另一个特定的类的例子. 默认情况下, Python 类是类类类的例子. 也就是说,类是大多数内置类的甲型类和用户定义类的甲型类。
class ListMetaclass(type):
def __new__(cls, name, bases, attrs):
attrs['add'] = lambda self, value: self.append(value)
return type.__new__(cls, name, bases, attrs)
class CustomList(list, metaclass=ListMetaclass):
pass
lst = CustomList()
lst.add('custom_list_1')
lst.add('custom_list_2')
lst
['custom_list_1', 'custom_list_2']
魔法将有效,当我们通过关键词论点在Metaclass,它指示Python翻译器通过ListMetaclass创建CustomList。新(),在此时,我们可以修改类定义,例如,并添加一个新的方法,然后返回修订的定义。
其他回答
型()函数可以返回对象的类型或创建一个新的类型,
例如,我们可以使用类()函数创建一个 Hi 类,并且不需要使用类 Hi(对象):
def func(self, name='mike'):
print('Hi, %s.' % name)
Hi = type('Hi', (object,), dict(hi=func))
h = Hi()
h.hi()
Hi, mike.
type(Hi)
type
type(h)
__main__.Hi
除了使用类()以动态创建类,您还可以控制类的创建行为,并使用甲塔克拉斯。
根据 Python 对象模型,类是对象,所以类必须是另一个特定的类的例子. 默认情况下, Python 类是类类类的例子. 也就是说,类是大多数内置类的甲型类和用户定义类的甲型类。
class ListMetaclass(type):
def __new__(cls, name, bases, attrs):
attrs['add'] = lambda self, value: self.append(value)
return type.__new__(cls, name, bases, attrs)
class CustomList(list, metaclass=ListMetaclass):
pass
lst = CustomList()
lst.add('custom_list_1')
lst.add('custom_list_2')
lst
['custom_list_1', 'custom_list_2']
魔法将有效,当我们通过关键词论点在Metaclass,它指示Python翻译器通过ListMetaclass创建CustomList。新(),在此时,我们可以修改类定义,例如,并添加一个新的方法,然后返回修订的定义。
Python 类本身是它们的 meta 类的对象 - 例如。
默认的金属类,当您确定类时应用于:
class foo:
...
例如,假设您正在构建一个ORM访问数据库,并且您希望每个表中的记录来自一个类地图到该表(基于字段,业务规则等),一个可能的使用MetaClass是例如,连接池逻辑,由所有表中的记录的所有类共享。
当你定义甲型时,你可以分类类型,并且可以超越下列魔法方法来插入你的逻辑。
class somemeta(type):
__new__(mcs, name, bases, clsdict):
"""
mcs: is the base metaclass, in this case type.
name: name of the new class, as provided by the user.
bases: tuple of base classes
clsdict: a dictionary containing all methods and attributes defined on class
you must return a class object by invoking the __new__ constructor on the base metaclass.
ie:
return type.__call__(mcs, name, bases, clsdict).
in the following case:
class foo(baseclass):
__metaclass__ = somemeta
an_attr = 12
def bar(self):
...
@classmethod
def foo(cls):
...
arguments would be : ( somemeta, "foo", (baseclass, baseofbase,..., object), {"an_attr":12, "bar": <function>, "foo": <bound class method>}
you can modify any of these values before passing on to type
"""
return type.__call__(mcs, name, bases, clsdict)
def __init__(self, name, bases, clsdict):
"""
called after type has been created. unlike in standard classes, __init__ method cannot modify the instance (cls) - and should be used for class validaton.
"""
pass
def __prepare__():
"""
returns a dict or something that can be used as a namespace.
the type will then attach methods and attributes from class definition to it.
call order :
somemeta.__new__ -> type.__new__ -> type.__init__ -> somemeta.__init__
"""
return dict()
def mymethod(cls):
""" works like a classmethod, but for class objects. Also, my method will not be visible to instances of cls.
"""
pass
无论如何,这两种是最常用的<unk>子,甲板是强大的,上面没有附近和完整的用途列表用于甲板。
在 Python 或任何其他语言中,我们对每个变量或对象都有一个类型. 在 Python 中,我们可以使用 Type() 函数来获得任何类型(变量、对象等)。
通过在课堂定义中的 meta 类关键词,我们可以自定义课堂创建过程。
class meta(type):
pass
class baseclass(metaclass=meta): # This is Mestaclass
pass
class derivedclass(baseclass):
pass
print(type(meta))
print(type(baseclass))
print(type(derivedclass))
在定义新类时,如果没有定义的甲型,则使用默认类型甲型;如果一个甲型不是类型(例)的对象(例),则在这种情况下,它直接用作甲型。
除了发布的答案,我可以说,一个甲状腺可以定义一个类的行为,所以,你可以明确设置你的甲状腺,每当Python获得一个关键词类,然后它开始搜索甲状腺,如果它没有找到 - 默认甲状腺类型用于创建一个类的对象,使用 __metaclass__属性,你可以设置你的甲状腺类:
class MyClass:
__metaclass__ = type
# write here other method
# write here one more method
print(MyClass.__metaclass__)
它将产生这样的产量:
class 'type'
当然,你可以创建自己的金属类来定义使用你的类创建的任何类的行为。
要做到这一点,您的默认金属类型类必须继承,因为这是主要金属类:
class MyMetaClass(type):
__metaclass__ = type
# you can write here any behaviour you want
class MyTestClass:
__metaclass__ = MyMetaClass
Obj = MyTestClass()
print(Obj.__metaclass__)
print(MyMetaClass.__metaclass__)
产量将是:
class '__main__.MyMetaClass'
class 'type'
简而言之:一类是创建一个例子的图标,一类是创建一个类的图标,可以很容易地看到,在Python类中,也需要第一类对象才能实现这种行为。
我从来没有自己写过一个,但我认为在Django框架中可以看到最可爱的用途之一。模型类使用一个模型类的方法,以允许写新的模型或形式类的宣言风格。
剩下的就是:如果你不知道什么是金属玻璃,那么你不需要它们的可能性是99%。
推荐文章
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字
- Pipenv:命令未找到
- 根据Pandas中的另一列提取列值
- virtualenv和pyenv是什么关系?