Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why function returns None?ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ ᅠ

Why does the cat1.set_size() function return None instead of "small" and the cat2.color function returns "<__ main __. Tiger object at 0x000002711C6D4DF0>" instead of "white"?

class Cat:
    def __init__(self, color, cat_type):
        self.size = "undefined"
        self.color = color
        self.cat_type = cat_type

    def set_size(self, cat_type):
        if self.cat_type == "indoor":
            self.size = "small"
        else:
            pass


class Tiger(Cat):
    def __init__(self, color, cat_type):
        super().__init__(color, cat_type)

    def set_size(self, cat_type):
        super().__init__(self, cat_type)
        if self.cat_type == "wild":
            self.size = "big"
        else:
            self.size = "undefined"


cat1 = Cat(color="black", cat_type="indoor")
cat1_size = cat1.set_size("indoor")
print(cat1.color, cat1.cat_type, cat1_size)

cat2 = Tiger(color="white", cat_type="wild")
cat2.set_size("wild")
print(cat2.color, cat2.cat_type, cat2.size)

Conclusion:

black indoor None
<__main__.Tiger object at 0x000002711C6D4DF0> wild big

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here’s a better organization.

class Cat:
    def __init__(self, color, cat_type):
        self.size = "undefined"
        self.color = color
        self.cat_type = cat_type

    def set_size(self):
        if self.cat_type == "indoor":
            self.size = "small"

class Tiger(Cat):
    def set_size(self):
        if self.cat_type == "wild":
            self.size = "big"

cat1 = Cat(color="black", cat_type="indoor")
cat1.set_size()
print(cat1.color, cat1.cat_type, cat1.size)

cat2 = Tiger(color="white", cat_type="wild")
cat2.set_size()
print(cat2.color, cat2.cat_type, cat2.size)

This still has problems, though. The size of the cat should not be determined by "wild" or "indoor". A Tiger, as a specific kind of Cat, should always have its size set to "big". You might have another subclass called Domestic that has its size set to "small".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading