1

Consider the following code, I want you to explain why the code doesn't work because I have seen others to assign the class attributes outside __init__ and call the attributes in one method from another, what is wrong with mine. The following three prints all result error saying the class has no attributes whatsoever.

class Person(object):
    def __init__(self, age, height):
        self.age = age
        self.height = height

    def weight_kg(self):
        self.weight = 60

    def ratio_kg2height(self):
        self.ratio = self.weight / self.height
        return self.ratio


mike = Person(23, 170)
print mike.weight
print mike.ratio_kg2height()
print mike.ratio
2
  • 1
    mike.weight isn't initialised until you call weight_kg. You'd need to make it a property. Commented May 13, 2018 at 16:33
  • Why do you believe that weight is going to be defined? Commented May 13, 2018 at 16:35

1 Answer 1

2

You are not defining the weight attribute in the __init__ method, since you dont call weight_kg method before accesing the attribute it is not available.

You have some options here, the basic one is to initialize it first, you can simply call your methods in the __init__ method:

class Person(object):
    def __init__(self, age, height):
        self.age = age
        self.height = height
        self.weight_kg()
        self.ratio_kg2height()

    ...

Here you have a live example

Sign up to request clarification or add additional context in comments.

8 Comments

When should I use the "hidden attributes" just as self.weight in this case?
@buzhidao what do you mean by "hidden attribute"? If you don't want an attribute error, then don't try to access an attribute until it is defined.
those are not hidden attributes, there are just late initialized.
@juanpa.arrivillaga when should I use the late initialized attributes?
@buzhidao, just use them when you are sure you will not need them in memory until some point...depends on what is the purpouse of your code. I would recommend not to do this, it can be a nightmare to maintain this kind of code, think of a coworker searching for the attributes of your class in all the methods for example. It is better to explicitly declare them, at least with default values, None or some kind of flag.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.