私有字段
class Foo: def __init__(self, name): self.__name = name def f1(self): print(self.__name) class Bar(Foo): def f2(self): print(self.__name) obj = Foo(‘alex‘)#print(obj.name)#只能内部调用obj.f1() obj2 = Bar(‘aaa‘)obj2.f1()#私有普通字段只有自己能访问,其余均不行obj2.f2()
静态方法
class Foo: __cc = ‘123‘ def __init__(self, name): self.__name = name def f1(self): print(self.__name) @staticmethod def f2(): print(Foo.__cc) # obj = Foo(‘aaa‘)# obj.f2()Foo.f2()
__getitem,__setitem,__delitem
class Foo: def __init__(self, name): self.__name = name def f1(self): print(self.__name) def __getitem__(self, item): print(type(item)) return 123 def __setitem__(self, key, value): print(‘setitem‘) def __delitem__(self, key): print(‘del item‘) obj = Foo(‘alex‘)#obj[]执行__getitem__方法#语法对应关系ret = obj[‘ad‘]print(ret)ret1 = obj[1:2]print(ret1)obj[‘k1‘] = 123del obj[‘k1‘]
切片
class Foo: def __init__(self, name): self.__name = name def f1(self): print(self.__name) def __getitem__(self, item): print(item, type(item)) print(item.start) print(item.stop) print(item.step) return 123 def __setitem__(self, key, value): #key.start key.stop key.step print(type(key), type(value)) def __delitem__(self, key): print(type(key)) # key.start key.stop key.step print(‘del item‘) obj = Foo(‘alex‘)#obj[]执行__getitem__方法#语法对应关系#ret = obj[‘ad‘]ret1 = obj[1:4:2]obj[1:4] = [11, 22, 33, 44, 55]del obj[1:4]
迭代器
class Foo: def __iter__(self): yield 1 yield 2 obj = Foo()for item in obj: print(item) #1.obj能被循环,必须被迭代#2.for循环执行时,默认执行__iter__方法
isinstance和issubclass
#isinstance:obj, Foo(obj类型和obj类型的父类)的实例#issubclass:是否子类class Foo: pass class Bar(Foo): pass obj = Bar()ret = isinstance(obj, Foo)print(ret) ret2 = issubclass(Bar, Foo)print(ret2)
super
#假设有一大堆代码,现在需要增加功能,不改变原来代码结构的基础上,增加类#然后执行super方法,super主动去执行父类的方法class C1: def f1(self): print(‘c1.f1‘) class C2(C1): def f1(self): #主动去执行父类的f1方法 super(C2, self).f1() print(‘c2.f1‘) #不建议使用该方法 #C1.f1(self) obj = C2()obj.f1()
在不改变原有框架的基础上,增加方法
框架结构:
Testbackendcommons.pyindex.pylib.py(自己扩展类)settings.py
commons.py
class Foo: def f1(self): print(‘Foo.f1‘)
settings.py
# Path = ‘backend.commons‘# ClassName = ‘Foo‘ Path = ‘lib‘ClassName = ‘MyFoo‘
lib.py
from backend.commons import Foo class MyFoo(Foo): def f2(self): print("before") super(MyFoo, self).f1() print("after")
index.py
from settings import ClassNamefrom settings import Path def execute(): #print(ClassName) #反射获取字符串 model = __import__(Path, fromlist=True) cls = getattr(model, ClassName) obj = cls() obj.f2() if __name__ == ‘__main__‘: execute()
有序字典
class MyDict(dict): def __init__(self): self.li = [] super(MyDict, self).__init__() def __setitem__(self, key, value): self.li.append(key) super(MyDict, self).__setitem__(key, value) def __str__(self): tmp_list = [] for key in self.li: value = self.get(key) tmp_list.append("‘%s‘:%s" % (key, value)) tmp_str = "{" + ",".join(tmp_list) + "}" return tmp_str obj = MyDict()obj[‘k1‘] = 123obj[‘k2‘] = 345print(obj)
时间: 2024-10-12 22:40:40