如何在不知道对象是什么的情况下在函数中使用对象

2024-04-19 08:47:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用一个对象,即使我不知道对象的名称。我尝试使用一个函数,它比较两个对象,看哪个对象的数量最大,但我希望能够将对象键入函数的参数中,然后函数进行比较,这样我就不必反复重复相同的代码。问题是,我不知道如何让函数中的一个参数说出要比较的对象。你知道吗

 class tester:
  myVar = None

  def __init__(self, myVar):
    self.myVar = myVar
  # I am not going to make everything legitamite here

def compare(first, second):
  # I want to make first = the first object i am comparing
  # second = second object i am comparing
  # I would then use it in a conditional

这可能不是最好的方法,如果有更好的方法,我很想知道。你知道吗


Tags: to对象方法函数self名称参数make
2条回答

一种更简洁的方法是在类中定义__cmp__()方法。这样,就可以在类实例上使用标准比较运算符< == != >等和内置的cmp()函数。另外,如果一个对象定义了__cmp__(),那么当传递给max()sort()这样的函数时,它的行为也会正常。(感谢EOL提醒我提到这一点)。你知道吗

例如

class tester(object):   
    def __init__(self, myVar):
        self.myVar = myVar

    def __cmp__(self, other):
        return cmp(self.myVar, other.myVar)


print tester(5) < tester(7)
print tester(6) == tester(6)
print tester(9) > tester(6)
print tester('z') < tester('a')
print cmp(tester((1, 2)), tester((1, 3)))

输出

True
True
True
False
-1

注意,我让tester从object继承,这使它成为new-style class。这不是绝对必要的,但它确实有各种好处。你知道吗

我还删除了myVar = Noneclass属性,正如EOL在注释中指出的那样,这是不必要的混乱。你知道吗

你的意思是你想传递一个类的两个实例,然后比较它们的值。如果是这样的话,你可以简单地做如下:

class tester:
  myVar = None
  def __init__(self, myVar):
    self.myVar = myVar

def compare(first, second):
  if first.myVar > second.myVar:
    return "First object has a greater value"
  elif first.myVar < second.myVar:
    return "Second object has a greater value"
  else:
   return "Both objects have the same value"

obj1 = tester(5)
obj2 = tester(7)

>>> print(compare(obj1, obj2))
#Output: Second object has a greater value

相关问题 更多 >