yandyand

导航

python 类方法和静态方法

#:静态方法:在调用类的时候就会自动执行

#:类方法:在调用的时候才会执行

class Person:
#:类属性
name = "jack"
def __init__(self,name):
self.name = name

def tell(self):
print(self.name)

@staticmethod
#:staticmethod 传入的是类中的属性
def talk():
print(Person.name) #:直接调用"Person类" 所以调用的是类的属性

@classmethod #:原理跟staticmethod一样都是可以传入一个类作为参数
def say(cls): #:但不同的是 这里传入的不再是类名 而是使用cls进行代指类名 cls就包含了你所调用的类
print(cls.name) #:这样的好处就是你可以随意的更改类名 如果你修改了类的名字那么staticmethod函数也需要修改,但classmethod就不需要"cls"==类




p = Person("yangyang")
p.tell()
p.talk()
p.say()


#使用@staticmethod/@classmethod对时间进行切分操作
'''
用户输入日期格式为:"2020-7-14"
需要将年,月,日分别打印出来
'''

class Dates:
def __init__(self,year = 0,morth = 0,day = 0):
self.year = year
self.morth = morth
self.day = day

@staticmethod
def get_date(string_date): #:数据进入到get_date方法中
year,morth,day = string_date.split("-") #:按照"-"进行切分
data1 = Dates(year,morth,day) #:实例化 将三个参数传入到Dates类中 == Dates("year","morth","day")
return data1 #:返回data1

def out_date(self): #:slef == Dates
print("year",self.year) #:打印Dates类中的.year属性
print("morth",self.morth) #:打印Dates类中的.morth属性
print("day",self.day) #:打印Dates类中的.day属性


if __name__ == '__main__':
years = Dates.get_date("2020-7-14") #:将值传入到get_date这个方法中
years.out_date() #:调用out_date方法


#:@classmethod
class Dates:
def __init__(self,year = 0,morth = 0,day = 0):
self.year = year
self.morth = morth
self.day = day

@classmethod #:调用classmethod函数
def get_date(cls,string): #:cls == 类 谁调用类 cls就等于谁
year,morth,day = string.split("-") #:切分操作
date1 = cls(year,morth,day) #: 将上面的"year","morth","day"三个变量传入到类里面
return date1 #:返回date1 // date 返回给 t t == Dates(year,morth,day)
#:print times
def out_date(self): #:slef == t
print("year",self.year) #:Dates.year
print("morth",self.morth) #:Dates.morth
print("day",self.day) #:Dates.day

if __name__ == '__main__':
years = input("input('year-morth,day')>>>")
t = Dates(years)
t.out_date()

posted on 2020-07-14 11:22  yandyand  阅读(202)  评论(0编辑  收藏  举报