【问题标题】:Can method operating on array of class object use array methods?对类对象数组进行操作的方法可以使用数组方法吗?
【发布时间】:2020-01-14 00:45:27
【问题描述】:

我是新来的,也是 Python 的新手。我的同事有一些 C/C++。我正在 udemy 上课程,我想知道是否有更好的想法来解决基于一个值查找类对象数组的元素的问题。课程任务是寻找“最古老的猫”。解决方案只是不使用列表/数组,但我想知道如何对对象数组进行操作,以及是否有比我的静态方法 getoldest 更好的选择,因为对我来说似乎我正在尝试“欺骗”python。

    class Cat:

    def getoldest(Cat=[]):
        age_table=[]
        for one in Cat:
            age_table.append(one.age)         
        return Cat[age_table.index(max(age_table))]

    def __init__(self, name, age):
        self.name = name
        self.age = age


# 1 Instantiate the Cat object with few cats
kotki3=[]
kotki3.append(Cat("zimka", 5))
kotki3.append(Cat("korek", 9))
kotki3.append(Cat("oczko", 10))
kotki3.append(Cat("kotek", 1))
kotki3.append(Cat("edward", 4))

# 2 Create a function that finds the oldest cat

oldest = Cat.getoldest(kotki3)

# 3 Print out: "The oldest cat is x years old.". x will be the oldest cat age by using the function in #2

print(f'The oldest cat is {oldest.name} and it\'s {oldest.age} years old')

非常感谢。

【问题讨论】:

  • 更直接的方法是在 cat 对象列表中使用 max()oldest = max(kotki3, key=lambda x: x.age)
  • 术语注释:这是一个列表,而不是一个数组。请注意,您的列表中没有“类对象”,类对象将是 类本身(它们是 Python 中的第一类对象,几乎所有东西都是 Python 中的对象)。列表中有你的类的实例。

标签: python arrays class methods


【解决方案1】:

我认为这个例子可以帮助你找到更好的方法

class Cat:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def get_details(self):
        return self.name, self.age


cats = [Cat("zimka", 5),
         Cat("oczko", 10),
         Cat("kotek", 1),
         Cat("edward", 4) ]

results = []
for cat in cats:
    (name, age) = cat.get_details()
    results.append((name,age))
print(sorted(results, key = lambda x: -x[1]))

【讨论】:

    【解决方案2】:

    您可以使用@classmethod,因此该函数将是静态的,并将类作为默认的第一个参数,以及在此处设为静态的_Instances 变量。

    当一个新的 Cat 被实例化时,它将被添加到 _Instances 列表中。

    class Cat:
        _Instances=[]
    
        @classmethod
        def getoldest(cls):
            _Instance = max(cls._Instances,key=lambda Instance: Instance.age)
            return ("Oldest {} is {}, and {} years old.".format(cls.__name__,_Instance.name,_Instance.age))
    
        def __init__(self, name, age):
            self.name = name
            self.age = age
            self.__class__._Instances.append(self)
    
    Cat("a",1)
    Cat("b",2)
    Cat("c",3)
    Cat("d",4)
    print(Cat.getoldest())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-28
      • 2022-01-18
      相关资源
      最近更新 更多