繁体   English   中英

在python的__init__中调用静态方法或属性

[英]call a static method or property in __init__ in python

我有很多问题! 看下面的代码plz:

class Dog(object):
    _the_most_oldest = int()

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


    @staticmethod   
    @property
    def the_most_oldest(age):
        if Dog._the_most_oldest < age:
            Dog._the_most_oldest=age
        return Dog._the_most_oldest

1:

属性是否可能是静态方法? 因为我需要一个在实例之间共享的静态变量-> _the_most_oldest dog! =>所以我需要@property。 并且因为the_most_oldest(age)方法不适用于任何特殊实例,所以我需要@staticmethod!

2:

我需要做的第二件事是在每个实例中调用the_most_oldest shuold并计算和刷新_the_most_oldest变量。 怎么办? 这有错误:

def __init__(self,age):
    self.age=age
    the_most_oldest(self.age)
  1. 在您的位置,我将初始化_the_most_oldest = 0 (也许可以将其_the_oldest ,更好的英语)
  2. 在您的情况下,Python中的@staticmethod只是一个“包含在类中”的函数,我认为使用@classmethod会更好。
  3. 如果要为属性分配值,则不能使用装饰器,需要传递一个setter和一个getter方法。

def _get_oldest(self):
        return self._the_oldest

def _set_oldest(self, age): if Dog._the_oldest < age: Dog._the_oldest=age the_oldest = property(_get_oldest, _set_oldest)

不,属性不能是静态方法(它不是描述符的方法)。

创建将保存该类的所有实例的类属性。

class Dog(object):
    _dogs = []

并将新实例放在_dogs类属性中。

def __init__(self, age):
    self._dogs.append(self)
    self.age = age

然后创建类方法 the_most_oldest 它将计算所有实例中最老的狗。

@classmethod
def the_most_oldest(cls):
    return max(cls._dogs, key=lambda dog: dog.age)

暂无
暂无

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

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