本文最后更新于 2022-05-26 11:25:30
Class
创建一个类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 class Student : """ 类注释 """ class_param="类的变量" _protect_param="protect" __private_param="private" def __init__ (self,name,age ): self .name=name self .age=age def info (self ): print (f"name: {self.name} , age:{self.age} " ) @classmethod def class_method (cls ): print (cls.class_param) @staticmethod def static_method (): print ("staticMethod" ) def __add__ (self, other ): var=Student("" ,0 ) var.age=self .age+other.age var.name=self .name+other.name return var def __str__ (self ): return f"age:{self.age} ,name:{self.age} ......." def __hello (self ): print ("hello" ) def _hh (self ): print ("hh" )
new 对象 1 stu = Student("king" , 123 )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 class Person (object ): def __new__ (cls, *args, **kwargs ): print (f"new 方法调用 classId->" , id (cls)) obj = super ().__new__(cls) print (f"创建对象的id->" , id (obj)) return obj def __init__ (self ): print (f"init方法调用 selfId->" , id (self ))print (f"object的id->" , id (object ))print (f"Person的id->" , id (Person)) p = Person()print (f"p的id为->" , id (p))
方法调用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 stu = Student("king" , 123 ) stu.info()print ("--------------" ) Student.info(stu) stu.static_method() stu.class_method() Student.static_method() Student.class_method()print (f"name->{stu.name} ,age->{stu.age} ,classParam->{Student.class_param} " )print (id (stu))print (type (stu))print (id (Student))print (type (Student))print ("-----------" ) stu2 = Student("123" , 123 ) stu3=stu + stu2print (stu3)print ("---------------" )print (Student.__doc__) print (Student.__name__) print (Student.__module__) print (Student.__bases__) print (Student.__base__) print (Student.__dict__) print (stu.__dict__) print (Student.__mro__) print (Student.__subclasses__) print ("==============" )print (stu._Student__private_param)print (stu._protect_param) stu._Student__hello() stu._hh()
动态绑定 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 stu = Student("king" , 123 ) stu.gender = "man" print (stu.gender) Student.zbc="ccc" print (Student.zbc+"__" )@classmethod def func1 (cls ): print ("这是类方法" ) Student.func1=func1 Student.func1() stu.func1()@staticmethod def func2 (): print ("这是静态方法" ) Student.func2=func2 Student.func2() stu.func2()def func3 (self ): print ("this %s's content is ............." %self .name) stu.func3 = types.MethodType(func3,stu) stu.func3() a=types.MethodType(func3,stu) a() stu.a=types.MethodType(func3,stu) stu.a()del stu.adelattr (stu,"func3" )
11class
https://jiajun.xyz/2020/10/29/python/01base/11class/