Can we overload behavior of class object

This question already has an answer here: What are metaclasses in Python? 14 answers You can use a metaclass: class SampleMeta(type): def __str__(cls): return ' I am a Sample class.' Python 3: class Sample(metaclass=SampleMeta): pass Python 2: class Sample(object): __metaclass__ = SampleMeta Output: I am a Sample class. A metaclass is the class of class. Its rela

我们可以重载类对象的行为吗?

这个问题在这里已经有了答案: Python中的元类是什么? 14个答案 您可以使用元类: class SampleMeta(type): def __str__(cls): return ' I am a Sample class.' Python 3: class Sample(metaclass=SampleMeta): pass Python 2: class Sample(object): __metaclass__ = SampleMeta 输出: I am a Sample class. 元类是类的类。 它与类的关系类似于类到实例的关系。 使用相同的class语句。

How does one create a metaclass?

This question already has an answer here: What are metaclasses in Python? 14 answers There are (at this point) two key methods in a metaclass: __prepare__ , and __new__ __prepare__ lets you supply a custom mapping (such as an OrderedDict ) to be used as the namespace while the class is being created. You must return an instance of whatever namespace you choose. If you don't imple

如何创建一个元类?

这个问题在这里已经有了答案: Python中的元类是什么? 14个答案 在这个元类中有两个关键的方法: __prepare__和 __new__ __prepare__允许您在创建类时提供用作名称空间的自定义映射(如OrderedDict )。 您必须返回您选择的任何名称空间的实例。 如果你没有实现__prepare__则使用正常的dict 。 __new__负责实际创建/修改最终课程。 一个简单的,不需要额外的元类将如下所示: class Meta(type): def __pr

How are Python metaclasses different from regular class inheritance?

This question already has an answer here: What are metaclasses in Python? 14 answers class AccessorType(type): def __init__(self, name, bases, d): type.__init__(self, name, bases, d) accessors = {} prefixs = ["get_", "set_", "del_"] for k in d.keys(): v = getattr(self, k) for i in range(3): if k.startswith(prefixs[i]

Python元类与常规类继承有什么不同?

这个问题在这里已经有了答案: Python中的元类是什么? 14个答案 class AccessorType(type): def __init__(self, name, bases, d): type.__init__(self, name, bases, d) accessors = {} prefixs = ["get_", "set_", "del_"] for k in d.keys(): v = getattr(self, k) for i in range(3): if k.startswith(prefixs[i]): a

Understanding metaclass and inheritance in Python

This question already has an answer here: What are metaclasses in Python? 14 answers 1) what is use of metaclass and when to use it? Metaclasses are to classes as classes are to objects. They are classes for classes (hence the expression "meta"). Metaclasses are typically for when you want to work outside of the normal constraints of OOP. 2) what is difference/similarity bet

了解Python中的元类和继承

这个问题在这里已经有了答案: Python中的元类是什么? 14个答案 1)元类的用途以及何时使用它? 元类是类,类是对象的类。 他们是类的类(因此表达“元”)。 元类通常用于当您想在OOP的正常约束之外工作时。 2)元类和继承之间有什么不同/相似之处? 元类不是对象的类层次结构的一部分,而基类是。 所以当一个对象执行“obj.some_method()”时,它不会在元类中搜索这个方法,然而元类可能是在类或对象创建期间创

How to run code when a class is subclassed?

This question already has an answer here: What are metaclasses in Python? 14 answers Classes (by default) are instances of type . Just as an instance of a class Foo is created by foo = Foo(...) , an instance of type (ie a class) is created by myclass = type(name, bases, clsdict) . If you want something special to happen at the moment of class-creation, then you have to modify the thing cr

当一个类被子类化时如何运行代码?

这个问题在这里已经有了答案: Python中的元类是什么? 14个答案 类(默认)是type实例。 就像Foo类的一个实例由foo = Foo(...)创建的那样, type实例(即类)由myclass = type(name, bases, clsdict) 。 如果你想在创建类的时候发生一些特殊的事情,那么你必须修改创建这个类的东西 - 即type 。 做到这一点的方法是定义一个type的子type - 即一个元类。 元类是它的类,因为类是它的实例。 在Python2中,你可以用一

Understanding a linear runtime implementation of anagram detection

I am learning about analysis of algorithms (python 2.7.6). I am reading a book (Problem solving with Algorithms and Data Structures) where Python is the language used for implementations. In Chapter 2, the author introduces algorithm analysis in a very clear and understandable way, and uses an anagram detection program as a template to compare different runtime implementations (quadratics, log

理解一个线性运行时实现的字谜检测

我正在学习算法分析(python 2.7.6)。 我正在阅读一本书(用算法和数据结构解决问题),其中Python是用于实现的语言。 在第2章中,作者以一种非常清楚易懂的方式介绍了算法分析,并使用一个谚语检测程序作为模板来比较不同的运行时实现(二次曲线,对数线性,线性)。 在线性和最有效的实现中,代码如下(我添加了注释): def anagram_test2(s1,s2): """ Checks if two strings are anagrams of each other Runs with O

How can you profile a script?

Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - ie, adding timing code to __main__ . What is a good way to profile how long a python program takes to run? Python includes a profiler called cProfile. It not only gives the total running time, but al

你如何描述脚本?

欧拉项目和其他编码竞赛往往有最长的时间来运行,或者人们吹嘘他们的特定解决方案的运行速度。 使用python,有时候这些方法有点奇怪 - 即将时间代码添加到__main__ 。 什么是一个好的方法来分析一个python程序需要运行多久? Python包含一个名为cProfile的分析器。 它不仅提供了总运行时间,而且还分别计算每个函数的时间,并告诉您每个函数被调用的次数,从而可以轻松确定应该在哪里进行优化。 你可以在代码中或者从解

Best way to filter a django QuerySet based on value without name (rank)

So I've build a web app with django, using postgres for the database. Using django.contrib.postgres.search.SearchRank , I search for all recipes in my database with the word 'chocolate', and it gives me back a nice sorted QuerySet. from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank # example code: # searching recipe_name: vector = SearchVector('recipe_n

根据名称过滤django QuerySet的最佳方式(等级)

所以我用django构建了一个web应用程序,使用postgres作为数据库。 使用django.contrib.postgres.search.SearchRank ,我搜索我的数据库中的所有食谱“巧克力”一词,它给了我一个很好的排序查询集。 from django.contrib.postgres.search import SearchVector, SearchQuery, SearchRank # example code: # searching recipe_name: vector = SearchVector('recipe_name') # searching for the term 'chocolate': query = SearchQue

How can I filter a date of a DateTimeField in Django?

I am trying to filter a DateTimeField comparing with a date. I mean: MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) I get an empty queryset list as an answer because (I think) I am not considering time, but I want "any time". Is there an easy way in Django for doing this? I have the time in the datetime setted, it is not 00:00 . Such lookups are implemented in

我如何过滤Django中DateTimeField的日期?

我想过滤一个DateTimeField比较日期。 我的意思是: MyObject.objects.filter(datetime_attr=datetime.date(2009,8,22)) 我得到一个空的查询集列表作为答案,因为(我认为)我不考虑时间,但我希望“随时”。 Django中有这样一个简单的方法吗? 我有时间在设定的日期时间,它不是00:00 。 这种查找在django.views.generic.date_based中实现,如下所示: {'date_time_field__range': (datetime.datetime.combine(date, dat

How do I do a not equal in Django queryset filtering?

In Django model QuerySets, I see that there is a __gt and __lt for comparitive values, but is there a __ne / != / <> ( not equals ?) I want to filter out using a not equals: Example: Model: bool a; int x; I want results = Model.objects.exclude(a=true, x!=5) The != is not correct syntax. I tried __ne , <> . I ended up using: results = Model.objects.exclude(a=true, x

如何在Django queryset过滤中做到不相等?

在Django模型的QuerySets中,我发现有一个__gt和__lt用于比较值,但是有一个__ne / != / <> ( 不等于 ?) 我想用不等于的方式过滤掉: 例: Model: bool a; int x; 我想要 results = Model.objects.exclude(a=true, x!=5) !=不正确的语法。 我试过__ne , <> 。 我结束了使用: results = Model.objects.exclude(a=true, x__lt=5).exclude(a=true, x__gt=5) 也许Q对象可以帮助解决这个问题。