Code interpretation and if self.isOpened: I wonder what this part means.

Asked 2 years ago, Updated 2 years ago, 13 views

class Fridge: isOpened = False foods = []

def open(self):
    self.isOpened = True
    print 'I opened the refrigerator door.'

def put(self, thing):
    if self.isOpened:   
        self.foods.append(thing)
        print 'There's food in the refrigerator...'
    else:
        print 'The refrigerator door is closed so I can't put it in...'

def close(self):
    self.isOpened = False
    print 'The refrigerator's closed...'

class Food: pass

In this code
def put(self, thing): if self.isOpened: ===> What does this mean? Is it false or true? I wonder why it was written like that.

python

2022-09-21 18:30

1 Answers

class Fridge:
    def put(self, thing):
        if self.isOpened: # <== If you write it like this,
class Fridge:
    Find isOpen = False # <==.
                     # It's on each fringe.
myFridge1 = Fridge()
myFridge2 = Fridge()

I made two refrigerators. It's Refrigerator 1 and Refrigerator 2. Refrigerator 1 and refrigerator 2 are different things. The self that refers to refrigerator 1 and refrigerator 2 itself depends on what kind of refrigerator it is.

myFridge1.isOpened
myFridge2.isOpened

isOpened above is whether refrigerator 1 is open, and isOpened below is whether refrigerator 2 is open. The . symbol is used to search for the right target (name) in the left target.

When defining a function, self was always used as the first factor. Let's not use it.

class Fridge:
    isOpened = False

    def shake():
        if isOpened:
            print("The effect was substantial!")
        else:
            print("It doesn't shake very well.").")

And let's shake it.

myFridge1.shake()

Let's take a look at isOpened in shake(). If you shake it like this, you don't know if it's open at the time of shaking, whether it's a refrigerator or two refrigerators, or if it's from the concept of a refrigerator itself.

So always in Python, when you call a function, the first factor is who calls it. That's self. (It goes in automatically even if you don't put it in.)

Now, let's put self as the first factor in the function so that we can see which refrigerator you shook.


class Fridge:
    isOpened = False

    def shake(self):
        if self.isOpened:
myFridge1.shake()

Now self in the defshake() function.Since you wrote isOpened, you can see that myFridge1 is self.


2022-09-21 18:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.