简体   繁体   English

将* class *作为函数参数传递

[英]Passing the *class* as function argument

I've never done this before, and it seems hacky, but I've tested and it does work. 我以前从未做过,而且看起来很笨拙,但是我已经测试过并且可以正常工作。 Is this considered OK form: 这是可以的形式吗:

from audio.models import audio
from document.models import pdf

def count_object_by_sha1(object_type, sha1):
    return object_type.objects.filter(sha1=sha1).count()

pdf_count = count_object_by_sha1(pdf, 'somesha1valuehere')
audio_count = count_object_by_sha1(audio, 'somesha1valuehere')

So basically, I'm passing the class to the function and using it to make a query on one or another django objects. 因此,基本上,我将类传递给函数,并使用它对一个或另一个django对象进行查询。 Feels like a hack...but it works and makes my code rather simple. 感觉就像是骇客……但是它可以使我的代码变得相当简单。

After running into the mutable object in function call issue, I'm a bit skittish about doing weird things with function arguments. 在遇到函数调用问题中的可变对象之后 ,我对使用函数参数做一些奇怪的事情有点不高兴。

That isn't what you're doing though. 那不是你在做什么。 You're passing a class, not a module. 您传递的是类,而不是模块。 pdf is evidently a Django model class, since it has an objects attribute. pdf显然是Django模型类,因为它具有objects属性。

Either way is fine, though. 不管哪种方法都可以。 Classes and modules are first class objects and it's perfectly OK to pass them around, use them in functions, etc. 类和模块是一流的对象,完全可以将它们传递,在函数中使用它们等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM