A
A
andreyNN2018-10-15 23:19:15
Python
andreyNN, 2018-10-15 23:19:15

How to get the initial value of an attribute?

response is a.__class__().health
for example

class Some_class:
    self.health = 15

a= Some_class()
a.health=10

how in such a situation to extract the initial value of health 15
a from an instance of a cannot be broken. a.__init__() is not appropriate.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
X
x67, 2018-10-16
@andreyNN

print(Some_class.health)
When an attribute value is assigned to an object a, the connection with the initial value is lost and it is impossible to get it through the object a, but it is still possible through the Some_class class. Here, however, there is a nuance ...
P.sy when declaring a static variable in a class, you do not need to write self
Self is needed inside methods and is a reference to an object so that you can interact with it inside a function through this reference

P
programmeraxel, 2018-10-16
@programmeraxel

For example, if health is dynamic and you want to get the value from the instance.

class SomeClass:
    def __init__(self, health=20):
        self._health = health
        self._init_health = self._health

    @property
    def health(self):
        return self._health

    @health.setter
    def health(self, value):
        self._health = value

    @property
    def init_health(self):
        return self._init_health

Either way
class SomeClass:
    def __init__(self, health=20):
        self._health = health

import inspect
inspect.getargspec(SomeClass.__init__)

But that won't work with a hardcore variable declaration like this.
self.health = 15

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question