How do i assign a variable in a python class?



  • Here's the code with the variable called flour:

    class Cake(object):
    
        flour = "wheat"
    
        def __init__(self, type, base):
            self.type = type
            self.base = base
    
        def mycake(self):
            print("This is the type of cake: " + self.type)
            print("This is the base layer of the cake: " + self.base)
    
    c1 = Cake('carrot', 'sponge')
    c1.mycake()
    
    c2 = Cake('fruit', 'sponge')
    c2.mycake()
    
    print(Cake.flour)
    

    The correct way to call the variable is using the class name "Cake.flour", here we are printing it, print(Cake.flour) The variable flour = "wheat" is available to all instances.

    Running the code above give the output:

    This is the type of cake: carrot
    This is the base layer of the cake: sponge
    This is the type of cake: fruit
    This is the base layer of the cake: sponge
    wheat


Log in to reply
 

© Lightnetics 2024