简体   繁体   English

在Python中将对象属性传递给函数的最优选方法是什么?

[英]What is the most preferred way to pass object attributes to a function in Python?

I am certain I am doing this "incorrectly" even though it works. 即使可以,我确定我正在“错误地”执行此操作。 Right now when I call a function I just pass the whole object ie 现在,当我调用一个函数时,我只是传递了整个对象,即

class my_file_obj:
    def __init__(self,filename):
        self.filename = filename
        self.owner = None
        self.file_type = None
        self.fileflag = 0
        self.md5 = None

The function call, where file_obj1 is an instance of my_file_obj : 函数调用,其中file_obj1my_file_obj的实例:

some_function(file_obj1)

and then referencing the attributes I need as needed within the function. 然后在函数中根据需要引用我需要的属性。

What is the "python"/correct way of doing this? 这样做的“ python” /正确方法是什么?

  • some_function(file_obj1)

  • some_function(file_obj1.filename)

  • the_filename = file_obj1.filename
    some_function(the_filename)

Well, it's quite obvious. 好吧,这很明显。 It depends on whether some_function needs the whole object or just the filename, in which case you pass the whole my_file_obj instance or just the filename. 这取决于some_function需要整个对象还是仅文件名,在这种情况下,您将传递整个my_file_obj实例或仅文件名。

I think some_function(file_obj1) is the most pythonic. 我认为some_function(file_obj1)是最pythonic的。

some_function(file_obj1.filename) doesn't pass the object to the function, it only passes the filename attribute as a string. some_function(file_obj1.filename)不会将对象传递给函数,而只会将filename属性作为字符串传递。 It then would require a lot of fiddly code to get the rest of the object's attributes. 然后,它将需要大量复杂的代码来获取对象的其余属性。

All the ways are acceptable and which you will choose will depend on your application (or design) choices. 所有方式都是可以接受的,您将选择哪种方式取决于您的应用程序(或设计)选择。

# with this call the file_obj1 object reference is sent to some_function()
some_function(file_obj1)

# with this call there is no pass by reference. If filename is a 
# string it is copied to some_function
some_function(file_obj1.filename)

# same as before, but here you are allocating a new var and copying the content
# to some_function
the_filename = file_obj1.filename
some_function(the_filename)

Or you may add a def __str__(self): return self.filename method to your class (because, maybe, printing a file object should return its name in your design anyways) and accept any kind of object for your function. 或者,您可以添加一个def __str__(self): return self.filename方法def __str__(self): return self.filename给您的类(因为,也许打印文件对象无论如何都要在您的设计中返回其名称),并接受函数的任何类型的对象。 The function then, for example, looks like this: 该函数例如如下所示:

def openFile(obj):
    return open(str(obj), 'rU')

Like this, the function accepts both strings and objects of your class. 像这样,该函数同时接受类的字符串和对象。 See http://en.wikipedia.org/wiki/Duck_typing . 参见http://en.wikipedia.org/wiki/Duck_typing

Not sure if this design is recommended -- just want to point out something less obvious. 不确定是否推荐这种设计-只是想指出一些不太明显的东西。 Maybe this is even pythonic? 也许这甚至是pythonic?

Well, it depends on what you want to do and what your goal is. 好吧,这取决于您想做什么以及您的目标是什么。

If you have a function that looks something like this: 如果您的函数看起来像这样:

def some_function(file_thingy):
   with open(file_thingy.filename, 'w') as f:
       f.write("Icky Icky Icky Patang NeeeeWom!")

Then it makes things much more generic - as long as you pass an object in that has a .filename attribute that is a string then your function will work. 然后,它使事情变得更加通用了-只要您传递的对象中具有.filename属性(它是字符串),然后您的函数就会起作用。 A more common example of this is when people talk about duck typing. 一个更常见的例子是人们谈论鸭的打字。 If it looks like a duck, walks like a duck, and quacks like a duck, well then it's a duck! 如果它看起来像鸭子,走路像鸭子,嘎嘎像鸭子,那么那就是鸭子!

So if you have the following function: 因此,如果您具有以下功能:

def do_duck_things(a_duck):
    print(a_duck.appearance)
    a_duck.waddle()
    a_duck.quack()
    print("It must be a duck!")

Then you could pass it an instance of: 然后,您可以将以下实例传递给它:

class Duck:
    def __init__(self):
        self.appearance = "White, like the AFLAC duck"

    def quack(self):
        print("Quaaaaaack!")

    def waddle(self):
        print("The duck waddles.")

or an instance of either of these classes: 或以下任一类的实例:

class UglyDuckling:
    def __init__(self):
        self.appearance = "Suspiciously like a baby goose"

    def waddle(self):
        print("The ugly duckling waddles a bit like a duck.")

    def quack(self):
        print("Hoooonk!")

class Human:
    def __init__(self):
        self.appearance = "Looks like a human in a duck costume"

    def waddle(self):
        print("Surprisingly, he waddles quite like a duck.")

    def quack(self):
        print("<A sound quite like Donald Duck would make>")

So in your case, it really depends on what your function should be doing. 因此,就您而言,这实际上取决于您的函数应该执行的操作。 If all it's doing is reading the contents of a file, then you can (and probably should) just send it a filename. 如果它所做的只是读取文件的内容,那么您可以(可能应该)只是发送一个文件名。 But if you want to do something like, say, check the file against your stored MD5, or set that MD5, then it's perfectly appropriate to pass in the object. 但是,如果您要执行类似的操作,例如,对照存储的MD5检查文件或设置该MD5,则完全适合传入对象。

HTH HTH

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

相关问题 将 object 层次结构导入 Python 的首选方式是什么 - What is the preferred way of importing object hierarchies into Python 在 Python function 中返回 boolean 的首选方法是什么? - What is the preferred way of returning a boolean in a Python function? 在此函数中传递kwargs的最pythonic方法是什么? - What is the most pythonic way to pass kwargs in this function? 在python 2.7的功能级别上导入pylab的首选方法是什么? - What is the preferred way to import pylab at a function level in Python 2.7? Python中最有效的方法是检查对象属性是否分配了DataFrames? - Most efficient way in Python to check if object attributes are assigned DataFrames? 将反应堆传递给Twisted中的协议的首选方式是什么? - What is the preferred way to pass the reactor to a protocol in Twisted? 修改属性的首选方法 - preferred way to modify attributes 在python中的模块之间传递对象的最合适方法是什么? - What is the most appropriate way to pass objects between modules in python? 在Python中,创建和管理线程的首选方法是什么? - In Python what is the preferred way to create and manage threads? 在Python中处理数据的首选方式是什么? - What is the preferred way to handle data in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM