簡體   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