ChickenFeet
ChickenFeet

Reputation: 2813

How to construct inner class from within static outer class

I have a static base class, which I want to encapsulate child classes. I cannot find the syntax to create the inner classes from within a static outer class.

Here's an example of what I want:

class Farm:
    my_pet_cat = Animal("Meeeeooowww", "Fluffy")

    class Animal:            
        def __init__(self, sound, fur):
            self.sound = sound
            self.fur = fur

        def speak(self):
            print(self.sound)

        def pet(self):
            return self.fur

NameError: name 'Animal' is not defined

I tried accessing Animal with self.Animal(...) but this didn't work, as obviously Farm doesn't have a self, being a static class and all. I also successfully accessed Animal if it is placed outside of Farm, but I want to encapsulate the Animal class within the Farm class.

Can this be done??

Upvotes: 0

Views: 69

Answers (2)

Charles Cao
Charles Cao

Reputation: 116

Why not use a module named Farm and in the Farm module, define a class name Animal?

Upvotes: 0

vishal
vishal

Reputation: 1205

Define Animal class before you reference it to create an instance.

class Farm:
    class Animal:            
        def __init__(self, sound, fur):
            self.sound = sound
            self.fur = fur

        def speak(self):
            print(self.sound)

        def pet(self):
            return self.fur

    my_pet_cat = Animal("Meeeeooowww", "Fluffy")

Upvotes: 3

Related Questions