0

I have many Questions ! look at this code 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 :

is it maybe that a property be a static method ?? beacuse I need a really static var that share between instances -> _the_most_oldest dog ! => so I need @property . and because the_most_oldest(age) method is not for any special instance I need @staticmethod !

2 :

the second thing I need to do is in every instace the_most_oldest shuold be call and calculate and refresh _the_most_oldest var. how do that ? this have Error :

def __init__(self,age):
    self.age=age
    the_most_oldest(self.age)
Ajay
  • 5,267
  • 2
  • 23
  • 30
Zero Days
  • 851
  • 1
  • 11
  • 22

2 Answers2

3
  1. In your place I would initialize _the_most_oldest = 0 (and maybe call it _the_oldest, better english)
  2. A @staticmethod in Python is just a function "contained in a class" in your case I think it would be better to use @classmethod.
  3. If you want to assign a value to a property you can not use the decorator, you need to pass a setter and a getter method.

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)

Andrea Corbellini
  • 17,339
  • 3
  • 53
  • 69
Oberix
  • 1,131
  • 7
  • 13
3

No, property can not be static method (it's not a method it's descriptor).

Create class attribute which will hold all instances of that class.

class Dog(object):
    _dogs = []

And put new instances in the _dogs class attribute.

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

And then create classmethod the_most_oldest. Which will calculate the most oldest dog of all instances.

@classmethod
def the_most_oldest(cls):
    return max(cls._dogs, key=lambda dog: dog.age)
Community
  • 1
  • 1
beezz
  • 2,398
  • 19
  • 15