简体   繁体   English

如何在 class 内部创建一个 function ,它可以告诉最大属性(年龄)及其对应的属性到这个最大年龄(即名称)?

[英]How to create a function inside the class which can tell maximum of an attribute (age) and its corresponding attribute to this max age (i.e. name)?

class Cat:
    species = 'mammal'
    def __init__(self, name, age):
        self.name = name
        self.age = age

cat1 = Cat('Billy', 2)
cat2 = Cat('John', 3)
cat3 = Cat('Kuro', 1)
print(cat1.name, cat1.age)
print(cat2.name, cat2.age)
print(cat3.name, cat3.age)

def oldest_age(*args):
    return max(args)
print(f'The oldest cat is {oldest_age(cat1.age, cat2.age, cat3.age)} years old.')

After doing all this, I get the following output which contains just the maximum age, but I want to also get the corresponding name of the cat which is the oldest.完成这一切之后,我得到了以下 output ,其中只包含最大年龄,但我还想获得最老的猫的相应名称。 How do i put is oldest-age function inside the class?我如何将最旧的 function 放入 class 中? Billy 2 John 3 Kuro 1 The oldest cat is 3 years old. Billy 2 John 3 Kuro 1 最老的猫是 3 岁。

WHAT I WANT AS OUTPUT Billy 2 John 3 Kuro 1 The oldest cat is John which is 3 years old.我想要什么 OUTPUT Billy 2 John 3 Kuro 1 最老的猫是 3 岁的 John。

You could use functools.reduce :你可以使用functools.reduce

from functools import reduce

def oldest_age(*cats):
    return reduce(lambda x, y: x if x.age > y.age else y, cats)

oldest_cat = oldest_age(cat1, cat2, cat3)
print(f'The oldest cat is {oldest_cat.name}, whose age is {oldest_cat.age} years old.')

You can use class attributes to keep track which cat is the oldest:您可以使用 class 属性来跟踪哪个猫是最古老的:

class Cat:
    oldest_name = None
    oldest_age = None
    
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    @property
    def age(self):
        return self._age
    
    @age.setter
    def age(self, val):
        self._age = val
        cls = self.__class__
        if  cls.oldest_age is None or self._age > cls.oldest_age:
            cls.oldest_age = self.age
            cls.oldest_name = self.name

Create some cats:创建一些猫:

cat1 = Cat('Billy', 2)
cat2 = Cat('John', 3)
cat3 = Cat('Kuro', 1)

Check for the oldest cat:检查最老的猫:

print(Cat.oldest_name, Cat.oldest_age)

It gives:它给:

John 3

Make Kuro older:让 Kuro 变老:

cat3.age = 10

Check for the oldest cat again:再次检查最老的猫:

print(Cat.oldest_name, Cat.oldest_age)

It gives:它给:

Kuro 10

暂无
暂无

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

相关问题 如何解析类属性的名称? - How can I parse a class attribute for its name? 如何将用户输入的姓名和年龄列表排序为具有相应姓名的平均年龄、最高年龄和最低年龄? - How to sort a list of names and ages as input from the user into average age, highest, and lowest age with corresponding name? python 如何同时计算年龄和姓名 function - python how to calculate age and name in one function 在SQLAlchemy Core中,如何创建表名与其属性不同的表? - In SQLAlchemy Core, how can I create a table with a column name that differs from its attribute? 如何从 csv 文件中找到最大年龄,然后返回该人的姓名? - How do I find the max age from a csv file and then return that person's name? 如何将出生年份的熊猫数据框列转换为年龄? (例如'1991'-> 28) - How can I convert a pandas dataframe column with birth year to age? (e.g. '1991' -> 28) 基本 OOP - 'str' object 没有属性 'age' - Basic OOP - 'str' object has no attribute 'age' 使用 Python 中的外部/帮助文件(即模块)修改 class 属性(自身)的最佳方法是什么? - What is the best way to modify a class attribute (self) using an external/helper file (i.e. module) in Python? 如何在基类中使用子类的函数属性? - How can I use a child class' function attribute in the base class? 如何覆盖在其父类中使用的子类中的属性? - How to override an attribute in a child class which is used in its parent class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM