Class methods, static methods and instance methods in Python

Class methods, static methods, and instance methods

1. Example method

First define a class Date that outputs the date, and then expand the content based on this class.

class Date:
    def __init__(self,year,month,day):
        self.year=year
        self.month=month
        self.day=day
	def __str__(self):
        return "{year}/{month}/{day}".format(year=self.year,month=self.month,say=self.day)
    
if __name__ == "__main__":
    new_day = Date(2018,12,30)
    print(new_day) # 2018/12/30   

Defined in the class are the example of the method under ordinary circumstances, such as in the code above __init__()and __str__()are examples of methods.

For example Date, define a new instance method in the class at the beginning tomorrow. This method increases the number of dates by one (the date is not judged here for simplicity).

def tomorrow(self):
    self.day += 1
    
if __name__ == "__main__":
    new_day = Date(2018,12,30)
    new_day.tomorrow() # python会自动转换成tomorrow(new_day)这种形式
    print(new_day) # 2018/12/31  

The instance method is to operate on the instance, the image self.变量+赋值符号becomes the variable of the instance object, and it is necessary to modify the class variable 类名.变量+赋值符号.

Two, static method

First introduce such a scenario, assuming that Datethe string parameter passed in by the class 2018-12-31looks like this. The incoming parameters that we defined at the beginning are separated by commas, so it definitely won't work.

In order to achieve this goal, the easiest way to think of is to use a splitfunction to process the string before putting it in.

date_str = "2018-12-30"
year, month, day = tuple(data_str.split("-"))
# print(year,month,day) # 2018 12 30
new_day = Date(int(year),int(month),int(day))
print(new_day) # 2018/12/30

It is conceivable that the Dateclass does not provide a method to convert a string into standard input. So there is a way to process it first and then input it.

This method has a big problem, that is, every time the Dateclass is instantiated, a piece of code (ie year, month, day = tuple(data_str.split("-"))) that handles the string needs to be added .

But in fact, we can put this logic in the class, that is, define static methods.

@staticmethod
def parse_from_string(data_str):
    year, month, day = tuple(data_str.split("-"))
    return Date(int(year),int(month),int(day))

The pythonstatic method does not need to receive self.

Because it is in Datethe namespace of the class, use Date.parse_from_string()to call

#用staticmethon完成初始化
new_day = Date.prase_from_string(date_str)
print(new_day) # 2018/12/30

At this point the code becomes concise, and new logic can be added to the static method. But the disadvantage of static methods is that they are hard-coded. If the class name is changed NewDate, then the return in the static method Datewill also change NewDate. It will be troublesome when there are many classes.

So there are class methods in Python.

Three, class method

@classmethod
def from_string(cls,data_str):
    year, month, day = tuple(data_str.split("-"))
    return cls(int(year),int(month),int(day))

__init__(self)What is passed in selfrefers to the object, and what is from_string()passed in clsrefers to the class itself. So this time returnhas nothing to do with the class name.

#用classmethon完成初始化
new_day = Date.prase_from_string(date_str)
print(new_day) # 2018/12/30

Do we think classmethodit can be completely replaced staticmethod?

staticmethodOf course, there are other uses. Let's imagine another scenario to determine whether the string is legal. This classmethodis also possible, but think more about it. The logic of judgment does not need to return the string object, and there is no need classmethonto clspass it in.

@staticmethod
def valid(data_str):
    year, month, day = tuple(data_str.split("-"))
    if int(year)>0 and (int(month)>0 and month<=12) and (int(day)>0 and int(day)<=31) #简单的逻辑,实际中判断是否合法不是这样的
    	return True
    elsereturn False
    
print(Date.valid_str("2018-12-32")) # False    

Subsection

Static method, a decorator needs to be added before the class method

Guess you like

Origin blog.csdn.net/weixin_43901214/article/details/106911827