Question about python classes


#1

i know i asked a lot of difficult questions lately, but i am curious about this code:

class exampleOne:
    def __init__(self):
        example_two = exampleTwo()
        print(example_two.x)

class exampleTwo:
    def __init__(self):
        self.x = "hello world"

example_one = exampleOne()

code for first question:

example_two = exampleTwo()

I create an instance of exampleTwo inside class exampleOne? This is possible? It seems to be.

code for second question:

print(example_two.x)

the instance then give me access to the methods, member variables and everything i add to self? Or do i understand this wrong?


#2

You're not making sense. For starters you're not doing anything in the first class since that code isn't being executed in your example

.. oh up there

Still no clue what you're asking though


#3

yea, this question has two sections:

the code, and the specific lines i have a question about

i can create instances of a class inside another class?


#4

That's statement with a question mark. I can't answer that!


#5

What's special about code inside a class?
I think the assumption should be that you can unless you have reason to think you can't


#6

And if you couldn't, why would you be able to create a string in a class? What would the difference be?


#7

nothing? I just find OOP still very confusing.

Okay, so assume it is possible until you get an error. Sounds fair


#8

No, more like, "You can instantiate classes."

Period, full stop.


#9

you can instantiate classes. Okay, make sense i guess. I will get more practice in OOP, that will hopeful make it easier :slight_smile:

Thank you ionatan :smiley:


#10

You know that you can instantiate classes. What's the reason for that you would not be able to do so in a class?


#11

yep, i know i can instantiate classes. I guess i got slightly confused. I had slightly more complex code, and just got a bit lost. Then i broke it down into the simpler code i posted in this topic, then we started talking about it, and all the puzzle pieces came together.

I should do that more often, simplify the code to better grasp the concept.

I guess i am just a slow learner, with sometimes bright moments where puzzle pieces come together.


#12

There isn't much to understand about oop

Classes contain the code to create instances.
Instances fall back to the class when attributes aren't found.
Classes fall back to parents when their attributes aren't found.

And an object is just a bundle of information, where one piece of information is its type so that this fallback behaviour can happen.

All classes inherit object, that's where the fallback stops