Object-oriented programming
Process-oriented: base code from top to bottom based on business logic
Functional: encapsulate a certain functional code into a function and call it directly later, no Need to write again
Object-oriented: Classify and encapsulate functions to make development "faster, better and stronger..."
# Programming languages such as Java and C# only Supports object-oriented programming, and Python supports a mixture of functional programming and object-oriented programming
Object-oriented example
# 函数式编程 def bar(): print('bar') bar() # 直接调用函数 # 面向对象编程 class Foo: # 创建类 def bar(self): # 在类里面定义函数 这里self是一个特殊的参数 创建对象时Foo将自身传进来 print('bar') obj = Foo() # 创建一个对象 obj.bar() # 由对象去访问类里面函数
The three major characteristics of object-oriented: encapsulation, inheritance, polymorphism
Encapsulation
Encapsulate the content we need into the created class, and call it when needed
class Foo: # 创建类 def __init__(self, name, age): # Foo接收到两个参数后会封装在自己类内部 self.name = name self.age = age obj = Foo('kobe', 18) # 创建一个对象 传两个参数 print(obj.name, obj.age) # 外面调用封装好的参数 输出: kobe 18
Class members
Fields: ordinary fields, static fields
Methods: ordinary methods, static methods, class methods
Attributes: ordinary attributes
1) Field (parameters encapsulated in the class)
class Foo: # 字段(静态字段 保存在类里面) CC = "中国" def __init__(self, name): # 字段(普通的字段 保存在对象里面) self.name = name # 普通字段通过对象访问 obj = Foo('上海') print(obj.name) # 静态字段通过类访问 print(Foo.CC)
2) Method (Functions encapsulated in the class)
class Foo: def show(self): # 普通方法:对象调用执行 方法属于类 print(self.name) @staticmethod def f1(): # 静态方法 由类调用执行 print('f1') @classmethod def f2(cls): # class 自动给类名传进去了 # 类方法 # cls 是类名 加()创建对象 print(cls) # 创建对象 obj = Foo() # 通过对象去访问普通方法 obj.show() # 通过类去访问静态方法 Foo.f1() # 类方法 会将类 Foo 名字直接传入函数 Foo.f2()
3) Attributes
Before defining the attributes of the class, we need to add brackets () after the method name when accessing the methods in the class: such as obj. f1()
After defining the attributes, we can access the methods in the class directly obj.f1
class Foo: @property def f1(self): print('f1') obj = Foo() obj.f1 # 无需加括号直接通过对象访问
Can be set and deleted
class Foo: @property # 在类方法上加上 property装饰器 def f1(self): print('f1') @f1.setter # 设置数值 def f1(self, values): print(values) @f1.deleter # 可删除 def f1(self): print('del...') obj = Foo() obj.f1 # 无需加括号直接通过对象访问 obj.f2 = 100 del obj.f1 输出: f1 del...
Another way to write class attributes
class Foo: def f1(self): return 100 def f2(self, value): print(value) def f3(self): print('300') # 类属性定义 Foo = property(fget=f1, fset=f2, fdel=f3) obj = Foo() # 取值 ret = obj.Foo print(ret) # 赋值 obj.Foo = 200 # 删除 del obj.Foo # 输出 100 200 300
Class member modifier
Class member modifier: Define fields or methods in the class as public or private
Public members: in Can be accessed anywhere
Private members: can only be accessed inside the class
class Foo: __cc = 123 def __init__(self, name): self.__name = name # 加两个下划线__表示私有字段 外部、继承都不能调用 def f1(self): print(self.__name) @staticmethod # 加 staticmethod 装饰器表示为静态方法,可以不加self参数直接外部调用 def f3(self): print(Foo.__cc) obj = Foo('kobe') # print(obj.__name) # 通过对象外部访问内部普通字段不成功 obj.f1() # print(Foo.__cc) # 通过外部访问内部静态字段也不成功 obj.f3() # 特殊访问方法 print(obj._Foo__name)
Special members of the class
__doc__ #Description information of the class
__module__ # Which module the current object is in
__class__ # Which class the current object belongs to
__str__ # The value returned when printing the object
__init__ # Constructor method
__del__ # Destruction method
__call__ # Adding parentheses after the object triggers execution
__dict__ # All members in the class or object
__getitem__ # Index operations such as dictionary
__setitem__ # Index operation
__delitem__ # Index operation
1) __doc__ description information
class Foo: """ 注释 __doc__ """ obj = Foo() print(obj.__doc__) 输出: 注释 __doc__ 2)__module__ 和 __class__ from lib.aa import C obj = C() print obj.__module__ # 输出 lib.aa,即:输出模块 print obj.__class__ # 输出 lib.aa.C,即:输出类
3)__init__ and __str__
class Foo: def __init__(self, name, age): # 构造方法 self.name = name self.age = age def __str__(self): # str方法 return '%s - %s ' % (self.name, self.age) obj1 = Foo(name='kobe', age=18) obj2 = Foo(name='jordan', age=18) print(obj1) print(obj2) # 输出: kobe - 18 jordan - 18
4) __del__
class Foo: def __init__(self, name, age): # 构造方法 self.name = name self.age = age # 析构方法:在垃圾回收之前执行 def __del__(self): pass
5) __call__
class Foo: def __call__(self, *args, **kwargs): print('call') p = Foo() # 对象后面加括号执行 __call__ 方法 p() # 一个括号是类创建了一个对象 两个括号是去执行 __call__ 方法 Foo()() # 输出: call call
6) __dict__
class Foo: def __init__(self, name, age): # 构造方法 self.name = name self.age = age obj1 = Foo(name='kobe', age=18) # 获取对象中封装的数据返回一个字典 ret = obj1.__dict__ print(ret) # 输出: {'name': 'kobe', 'age': 18} # 全部的类方法 # print(Foo.__dict__)
6) __getitem__ __setitem__ delitem__ used for index operations, such as dictionaries: yes Get value, set, delete
class Foo: def __getitem__(self, item): print('getitem') def __setitem__(self, key, value): print('setitem') print(item.start, item.stop, item.step) def __delitem__(self, key): print('delitem') # 中括号语法自动执行 getitem 方法 obj = Foo() obj['ab'] # 中括号并且赋值执行 setitem 方法 obj['k1'] = 111 del obj['k1'] # 切片也是去执行 setitem 方法 obj[1:6:2] # 输出 setitem delitem getitem 1 6 2
7) __iter__, __isinstance__, __issubclass__
class Bar: pass class Foo(Bar): # 返回一个可迭代对象 def __iter__(self): # return iter([11, 22, 33, 44]) yield 1 yield 2 obj = Foo() for item in obj: print(item) # 查看 obj 是否是 Foo 的实例 ret = isinstance(obj, Foo) # 也可以查看是否是 父类 的实例 # ret = isinstance(obj, Bar) print(ret) # 查看 Foo 是否为 Bar 的子类 ret1 = issubclass(Foo, Bar) print(ret1) # 输出 1 2 True True
super
super is to solve the multiple inheritance problem in Python and force the execution of the parent class Method in
class C1: def f1(self): print('c1.f1') class C2(C1): def f1(self): # 主动执行父类的 f1 方法 super(C2, self).f1() print('c2.f1') obj = C2() obj.f1() # 输出: c1.f1 c2.f1
Use super to add functions without changing the source code
目录 backend - commons.py index.py lib.py setting.py commons.py >> class Foo: def f1(self): print('Foo.f1') index.py >> from setting import ClassName from setting import Path def execute(): model = __import__(Path, fromlist=True) cls = getattr(model, ClassName) obj = cls() obj.f1() if __name__ == '__main__': execute() setting >> # Path = "backend.commons" # ClassName = 'Foo' Path = "lib" ClassName = 'MyFoo' lib >> from backend.commons import Foo class MyFoo(Foo): def f1(self): print('before') super(MyFoo, self).f1() print('after') 这样运行我们自己添加的lib 时结果如下 before Foo.f1 after
Use super to implement an ordered dictionary
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): temp_list = [] for key in self.li: value = self.get(key) temp_list.append("'%s':%s" % (key, value)) temp_str = "{" + ",".join(temp_list) + "}" return temp_str obj = MyDict() obj['k1'] = 123 obj['k2'] = 456 print(obj) # 输出 {'k1':123,'k2':456}
Single case mode
# The singleton pattern is a commonly used software design pattern. It contains only one special class called a singleton class in its core structure. The singleton mode can ensure that there is only one instance of a class in the system and that the instance is easy to access from the outside world, thereby facilitating control of the number of instances and saving system resources. If you want only one object of a certain class to exist in the system, the singleton pattern is the best solution.
class Foo: instance = None def __init__(self, name): self.name = name @classmethod def get_instance(cls): if cls.instance: return cls.instance else: obj = cls('alex') cls.instance = obj return obj obj1 = Foo.get_instance() obj2 = Foo.get_instance() print(obj1) print(obj2) # 输出 <__main__.Foo object at 0x000001C09B130B70> <__main__.Foo object at 0x000001C09B130B70>
Exception handling
while True: num1 = input('num1: ') num2 = input('num2: ') try: num1 = int(num1) num2 = int(num2) ret = num1 + num2 except Exception as ex: print(ex) except ValueError as ex: print(ex) except IndexError as ex: print(ex)
Exception handling complete code
try: raise Exception('主动错误一下...') pass except ValueError as ex: print(ex) except Exception as ex: print(ex) else: pass finally: pass
The above is the detailed content of Detailed explanation of object-oriented automated operation and maintenance Python series. For more information, please follow other related articles on the PHP Chinese website!