简体   繁体   中英

Understanding class method in python

I have a three question to ask

  1. in python I have written a class method inside a class and have written basic functionality When I try to call that method from class itself and when I try to print I get the output as "None"
  2. Also if someone can please explain in class methods only class variables can be accessed? and also can instance variables can also be accessed in class methods
  3. Also if remove the class variables and declare my own variables in the class method would the code will work when i pass the arguments in the method while calling it from class

Below is the code

class Item():

    discount_price = 0.8
    quantity1 = 10
    quantity2 = 10
    
    def __init__(self,name,price,quantity):
        self.name = name
        self.price = price
        self.quantity = quantity


    @classmethod
    def year2020(cls,val1,val2):
         cls.value2020 = cls.quantity1 + cls.quantity2 + cls.discount_price
        

print(Item.year2020(10,10))

The functoin year2020 does not return anything, so the print statement is told to print out nothing. To get it to print the output of the function, make sure to include a return statement inside.

For example, here is a fixed function which returns the output:

def year2020(cls,val1,val2):
    cls.value2020 = cls.quantity1 + cls.quantity2 + cls.discount_price
    return cls.value2020

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM