#encoding=utf-8 class Foo: def __init__(self, name): self.name = name def ord_func(self): """ 定义普通方法,至少有一个self参数 """ # print self.name print (‘普通方法‘) @classmethod def class_func(cls): """ 定义类方法,至少有一个cls参数 """ print (‘类方法‘) @staticmethod def static_func(): """ 定义静态方法 ,无默认参数""" print (‘静态方法‘) f=Foo("吴老师") f.ord_func() Foo.class_func() f.class_func() Foo.static_func() f.static_func()
class Person: def __init__(self,name,gender): self.name = name self.gender = gender def get_name(self): #实例方法,必须要实例化才能使用 return self.name #调用实例方法的第一种写法:直接用类名+实例化调用 print(Person("吴老师","Male").get_name()) #但是这种方法实例没有存到变量里,所以只能使用一次 #调用实例方法的第二种写法:1.先做实例化;2.用实例名+方法名 wulaoshi = Person("吴老师","Male") #实例化 print(wulaoshi.get_name())
class Person: count = 0 #类变量 def __init__(self,name,gender): self.name = name self.gender = gender Person.count +=1 def get_name(self): return self.name #类方法:可以使用类变量,不能使用实例变量-----这是为什么呢?:参数没有self,找不到实例的地址,因此不能用实例变量 @classmethod #加classmethod才能标识为类方法 def get_instance_count(cls): return Person.count @classmethod def create_a_instance(cls): return Person("张","女") #类方法里虽然不可以使用实例变量,但是可以创建实例 print(Person.count) Person("吴老师","Male") print(Person.count) print(Person.get_instance_count()) #用类调用 print(Person("吴老师","Male").get_instance_count()) #用实例调用
class Person: count = 0 #类变量 nation = "中国" def __init__(self,name,gender): self.name = name self.gender = gender Person.count +=1 def get_name(self):#实例方法,必须要实例化 return self.name @staticmethod #静态方法:不需要self和cls def get_nation(): return Person.nation print(Person.get_nation()) #类名调用 print(Person("吴老师","Male").get_nation()) #实例调用
class FileUtil: @staticmethod def get_file_name(file_path): with open(file_path) as fp: return fp.name @staticmethod def get_file_content(file_path): with open(file_path,encoding="utf-8") as fp: return fp.read() print(FileUtil.get_file_name("e:\\a.txt")) print(FileUtil.get_file_content("e:\\a.txt"))
原文:https://www.cnblogs.com/wenm1128/p/11716219.html