Python:如何防止作为函数的类变量被理解为方法?

发布于 2024-09-19 12:52:53 字数 681 浏览 4 评论 0原文

我目前正在实现一个 django 应用程序,为此我尝试使用与 Django 一致的语法...

所以这就是我正在尝试的:

class Blablabla(Model):

    #this contains Blablabla's options
    class Meta:
        sort_key = lambda e: e

sort_key 是一个关键函数(用于排序目的),但当然,它被理解为Meta的方法(这绝对不是我想要的)!

有什么解决方法,仍然允许我使用这种语法吗?

编辑 : 只是一个重要的精度......我编写的代码应该是由使用该库的人编写的!这就是为什么我不想要任何肮脏的伎俩。是的,在 Django 中它确实只用于选项......当然 Meta 是一个类,但我说“它不被视为一个类”,因为它不被用作一个类:你不实例化它,你不放置类方法,只放置类属性... Model 有一个元类,它从这个 Meta 中提取所有内容并处理声明的所有选项...全部 !它只是选项的占位符。

但好吧,这是真的,我从未见过 Django 中的函数选项...所以我将按照 Ned 声明此排序函数作为 Model 的方法,该方法具有被覆盖...

I am currently implementing a django app, for this I try to use a syntax that is consistent with Django's...

So here is what I am trying :

class Blablabla(Model):

    #this contains Blablabla's options
    class Meta:
        sort_key = lambda e: e

sort_key is a key function (for sorting purposes), but of course, it is understood as Meta's method (which is absolutely not what I want)!!!

Any workaround to this, that would still allow me to use this syntax ?

EDIT :
Just an important precision ... the code I wrote is supposed to be written by somebody that uses the library ! That's why I don't want any dirty trick. And YES in Django it is really used just for options... of course Meta IS a class, but I say "it is not seen as a class", because it is not used as a class : you don't instantiate it, you don't put class methods, only class attributes... The Model has a metaclass that extracts everything from this Meta and handles all the options declared... But that's all ! It IS just a placeholder for options.

But OK that's True I never saw an option that is a function in Django... So I'll follow Ned an declare this sorting function as a method of Model that has to be overriden ...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

作死小能手 2024-09-26 12:52:53

为什么要尝试将 sort_key 放入 Meta 中? Meta 用于 Django 选项,它不是放置您自己的方法的地方。模型可以具有在其上定义的方法。我想你想要的东西就像这样简单:

class Blablabla(Model):

    def sort_key(self, e):
        return e

Why are you trying to put sort_key into Meta? Meta is used for Django options, it isn't a place to put your own methods. Models can have methods defined on them. I think you want something as simple as:

class Blablabla(Model):

    def sort_key(self, e):
        return e
原谅我要高飞 2024-09-26 12:52:53

一般来说,

class Meta(object):
    sort_key= staticmethod(lambda e: e)

我不知道 Django 为移植“元”成员所做的任何魔法是否可以很好地处理这样的装饰方法,但我没有看到任何内在的原因。

In general,

class Meta(object):
    sort_key= staticmethod(lambda e: e)

I've no idea if whatever magic Django does to transplant ‘meta’ members copes OK with decorated methods like this, but I don't see any inherent reason why not.

简单 2024-09-26 12:52:53

OP 在评论中写道“‘Meta’实际上不应该被视为一个类”。如果是这样的话,也就是说,如果当 Meta 确实不是一个类时 Django 能够生存下来(一个很大的“如果”),那么就有可能满足 OP 的真正需求。奇怪的愿望是避免使用最简单的解决方案(只需将 stqticfunction 包裹在有问题的 lambda 周围)。

本质上,这需要编写一个(非常奇怪的)类来生成一个对象,其中属性查找绕过类对描述符对象的正常使用(每个函数都是一个描述符对象:也就是说,它有一个 __get__ 方法,Python 在查找属性时通常使用该方法在类或其实例上)。

这种荒谬的旋转的总体思路类似于......:

class MetaNotAClass(type):
   def __new__(mcl, clasname, bases, clasdict):
     if bases:
         usedict = {}
     else:
         usedict = clasdict
     usedict['__foo'] = clasdict
     return type.__new__(mcl, clasname, bases, usedict)
   def __getattr__(cls, atname):
      try: return getattr(cls, '__foo')[atname]
      except KeyError: raise AttributeError, atname

class NotAClass:
  __metaclass__ = MetaNotAClass


class Bah(NotAClass):
  def f(): return 'weird!'

print Bah.f()

当然,任何期望Bah成为类的东西都会崩溃(但是,你确实说它“实际上不应该被视为一个类”,所以这基本上就是你所要求的:打破任何认为它“被视为一个类”的代码班级”!-)。

The OP writes in a comment "'Meta' is not really supposed to be seen as a class". If that's the case, that is, if Django can survive when Meta is indeed not a class (a very big "if"), then it's possible to satisfy the OP's truly weird desire to avoid the simplest solution (just wrapping stqticfunction around the lambda in question).

Essentially, this requires writing a (pretty weird) meta-class that generates an object where attribute lookup bypasses a class's normal use of descriptor objects (every function is a descriptor object: that is, it has a __get__ method which Python normally uses when looking up attribute on the class or an instance thereof).

The general idea of this absurd gyration would be something like...:

class MetaNotAClass(type):
   def __new__(mcl, clasname, bases, clasdict):
     if bases:
         usedict = {}
     else:
         usedict = clasdict
     usedict['__foo'] = clasdict
     return type.__new__(mcl, clasname, bases, usedict)
   def __getattr__(cls, atname):
      try: return getattr(cls, '__foo')[atname]
      except KeyError: raise AttributeError, atname

class NotAClass:
  __metaclass__ = MetaNotAClass


class Bah(NotAClass):
  def f(): return 'weird!'

print Bah.f()

Of course, anything that expects Bah to be a class will break (but then, you do say it's "not really supposed to be seen as a class", so that's basically what you're asking for: to break any code that believes it is "to be seen as a class"!-).

时光倒影 2024-09-26 12:52:53

难道您不能只创建一个简单的模块(meta?)并向其中添加 sort_key 吗?然后继续在您需要的任何地方包含它......

Can't you just create a simple module (meta?) and add sort_key to it? Then go ahead and include it wherever you need it...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文