36带参数和不带参数的 Python 装饰器
def someDecorator(arg=None): def decorator(func): def wrapper(*a, **ka): if not callable(arg): print(arg) return func(*a, **ka) else: return 'xxxxx' return wrapper if callable(arg): return decorator(arg) # return 'wrapper' else: return decorator # ... or 'decorator' @someDecorator(arg=1) def my_func(): print('my_func') @someDecorator def my_func1(): print('my_func1') if __name__ == "__main__": my_func() my_func1()
Output:
1 my_func
37Python 中带有 self 参数的类方法装饰器
def check_authorization(f): def wrapper(*args): print('Inside wrapper function argement passed :', args[0].url) return f(*args) return wrapper class Client(object): def __init__(self, url): self.url = url @check_authorization def get(self): print('Inside get function argement passed :', self.url) Client('Canada').get()
Output:
Inside wrapper function argement passed : Canada Inside get function argement passed : Canada
38在 Python 中的另一个类中使用隐藏的装饰器
class TestA(object): def _decorator(foo): def magic(self): print("Start magic") foo(self) print("End magic") return magic @_decorator def bar(self): print("Normal call") _decorator = staticmethod(_decorator) class TestB(TestA): @TestA._decorator def bar(self): print("Override bar in") super(TestB, self).bar() print("Override bar out") print("Normal:") test = TestA() test.bar() print('-' * 10) print("Inherited:") b = TestB() b.bar()
Output:
Normal: Start magic Normal call End magic ---------- Inherited: Start magic Override bar in Start magic Normal call End magic Override bar out End magic
39装饰器内部的 self 对象
import random def only_registered_users(func): def wrapper(handler): print('Checking if user is logged in') if random.randint(0, 1): print('User is logged in. Calling the original function.') func(handler) else: print('User is NOT logged in. Redirecting...') return wrapper class MyHandler(object): @only_registered_users def get(self): print('Get function called') m = MyHandler() m.get()
Output:
Checking if user is logged in User is logged in. Calling the original function. Get function called
40在 Python 中将多个装饰器应用于单个函数
def multiplication(func): def wrapper(*args, **kwargs): num_sum = func(*args, **kwargs) print("Inside the multiplication function", num_sum) return num_sum * num_sum return wrapper def addition(func): def wrapper(*args, **kwargs): num_sum = func(*args, **kwargs) print("Inside the addition function", num_sum) return num_sum + num_sum return wrapper @addition @multiplication def calculation(a): print("Inside the calculation function", a) return a print("Sum =", calculation(5))
Output:
Inside the calculation function 5 Inside the multiplication function 5 Inside the addition function 25 Sum = 50
41Python 装饰器获取类实例
class MySerial(): def __init__(self): pass # I have to have an __init__ def write(self, *args): print(args[0]) pass # write to buffer def read(self): pass # read to buffer @staticmethod def decorator(func): def func_wrap(cls, *args, **kwargs): cls.ser.write(func(cls, *args, **kwargs)) return cls.ser.read() return func_wrap class App(): def __init__(self): self.ser = MySerial() @MySerial.decorator def myfunc(self): self = 100 return ['canada', 'australia'] App().myfunc()
Output:
['canada', 'australia']
42init 和 call 有什么区别
class Counter: def __init__(self): self._weights = [] for i in range(0, 2): self._weights.append(1) print(str(self._weights[-2]) + " No. from __init__") def __call__(self, t): self._weights = [self._weights[-1], self._weights[-1] + self._weights[-1]] print(str(self._weights[-1]) + " No. from __call__") num_count = Counter() for i in range(0, 4): num_count(i)
Output:
1 No. from __init__ 2 No. from __call__ 4 No. from __call__ 8 No. from __call__ 16 No. from __call__
43在 Python 中使用 new 和 init
class Shape: def __new__(cls, sides, *args, **kwargs): if sides == 3: return Triangle(*args, **kwargs) else: return Square(*args, **kwargs) class Triangle: def __init__(self, base, height): self.base = base self.height = height def area(self): return (self.base * self.height) / 2 class Square: def __init__(self, length): self.length = length def area(self): return self.length*self.length a = Shape(sides=3, base=2, height=12) b = Shape(sides=4, length=2) print(str(a.__class__)) print(a.area()) print(str(b.__class__)) print(b.area())
Output:
class '__main__.Triangle' 12.0 class '__main__.Square' 4
44Python 中的迭代重载方法
class Counter: def __init__(self, low, high): self.current = low self.high = high def __iter__(self): return self def __next__(self): if self.current > self.high: raise StopIteration else: self.current += 1 return self.current - 1 for num in Counter(5, 15): print(num)
Output:
5 6 .. .. 15
45在 Python 中使用迭代器反转字符串
class Reverse: def __init__(self, data): self.data = data self.index = len(data) def __iter__(self): return self def __next__(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index] test = Reverse('Python') for char in test: print(char)
Output:
n o h t y P
46Python 中 reversed 魔术方法
class Count: def __init__(self, start, end): self.start = start self.end = end self.current = None def __iter__(self): self.current = self.start while self.current < self.end: yield self.current self.current += 1 def __next__(self): if self.current is None: self.current = self.start if self.current > self.end: raise StopIteration else: self.current += 1 return self.current-1 def __reversed__(self): self.current = self.end while self.current >= self.start: yield self.current self.current -= 1 obj1 = Count(0, 5) for i in obj1: print(i) obj2 = reversed(obj1) for i in obj2: print(i)
Output:
0 1 2 .... 2 1 0
47Python 中的 getitem 和 setitem
class Counter(object): def __init__(self, floors): self._floors = [None]*floors def __setitem__(self, floor_number, data): self._floors[floor_number] = data def __getitem__(self, floor_number): return self._floors[floor_number] index = Counter(4) index[0] = 'ABCD' index[1] = 'EFGH' index[2] = 'IJKL' index[3] = 'MNOP' print(index[2])
Output:
IJKL
48在 Python 中使用 getattr 和 setattr 进行属性赋值
class Employee(object): def __init__(self, data): super().__setattr__('data', dict()) self.data = data def __getattr__(self, name): if name in self.data: return self.data[name] else: return 0 def __setattr__(self, key, value): if key in self.data: self.data[key] = value else: super().__setattr__(key, value) emp = Employee({'age': 23, 'name': 'John'}) print(emp.age) print(emp.name) print(emp.data) print(emp.salary) emp.salary = 50000 print(emp.salary)
Output:
23 John {'age': 23, 'name': 'John'} 0 50000
49什么是 del 方法以及如何调用它
class Employee(): def __init__(self, name='John Doe'): print('Hello ' + name) self.name = name def developer(self): print(self.name) def __del__(self): print('Good Bye ' + self.name) emp = Employee('Mark') print(emp) emp = 'Rocky' print(emp)
Output:
Hello Mark <__main__.Employee object at 0x00000000012498D0> Good Bye Mark Rocky
50创建类的私有成员
class Test(object): __private_var = 100 public_var = 200 def __private_func(self): print('Private Function') def public_func(self): print('Public Function') print(self.public_var) def call_private(self): self.__private_func() print(self.__private_var) t = Test() print(t.call_private()) print(t.public_func())
Output:
Private Function 100 None Public Function 200 None
51一个 Python 封装的例子
class Encapsulation: __name = None def __init__(self, name): self.__name = name def get_name(self): return self.__name pobj = Encapsulation('Rocky') print(pobj.get_name())
Output:
Rocky
52一个 Python 组合的例子
class Salary: def __init__(self, pay): self.pay = pay def get_total(self): return (self.pay*12) class Employee: def __init__(self, pay, bonus): self.pay = pay self.bonus = bonus self.obj_salary = Salary(self.pay) def annual_salary(self): return "Total: " + str(self.obj_salary.get_total() + self.bonus) obj_emp = Employee(600, 500) print(obj_emp.annual_salary())
Output:
Total: 7700
53一个Python聚合的例子
class Salary: def __init__(self, pay): self.pay = pay def get_total(self): return (self.pay*12) class Employee: def __init__(self, pay, bonus): self.pay = pay self.bonus = bonus def annual_salary(self): return "Total: " + str(self.pay.get_total() + self.bonus) obj_sal = Salary(600) obj_emp = Employee(obj_sal, 500) print(obj_emp.annual_salary())
Output:
Total: 7700
54Python 中的单级、多级和多级继承
# Single inheritence class Apple: manufacturer = 'Apple Inc' contact_website = 'www.apple.com/contact' name = 'Apple' def contact_details(self): print('Contact us at ', self.contact_website) class MacBook(Apple): def __init__(self): self.year_of_manufacture = 2018 def manufacture_details(self): print('This MacBook was manufactured in {0}, by {1}.' .format(self.year_of_manufacture, self.manufacturer)) macbook = MacBook() macbook.manufacture_details() # Multiple inheritence class OperatingSystem: multitasking = True name = 'Mac OS' class MacTower(OperatingSystem, Apple): def __init__(self): if self.multitasking is True: print('Multitasking system') # if there are two superclasses with the sae attribute name # the attribute of the first inherited superclass will be called # the order of inhertence matters print('Name: {}'.format(self.name)) mactower = MacTower() # Multilevel inheritence class MusicalInstrument: num_of_major_keys = 12 class StringInstrument(MusicalInstrument): type_of_wood = 'Tonewood' class Guitar(StringInstrument): def __init__(self): self.num_of_strings = 6 print('The guitar consists of {0} strings,' + 'it is made of {1} and can play {2} keys.' .format(self.num_of_strings, self.type_of_wood, self.num_of_major_keys)) guitar = Guitar()
Output:
This MacBook was manufactured in 2018, by Apple Inc. Multitasking system Name: Mac OS The guitar consists of 6 strings, it is made of Tonewood and can play 12 keys.
55在 Python 中获取一个类的父类
class A(object): pass class B(object): pass class C(A, B): pass print(C.__bases__)
Output:
(< class '__main__.A' >, < class '__main__.B' >)
56Python 中的多态性
# Creating a shape Class class Shape: width = 0 height = 0 # Creating area method def area(self): print("Parent class Area ... ") # Creating a Rectangle Class class Rectangle(Shape): def __init__(self, w, h): self.width = w self.height = h # Overridding area method def area(self): print("Area of the Rectangle is : ", self.width*self.height) # Creating a Triangle Class class Triangle(Shape): def __init__(self, w, h): self.width = w self.height = h # Overridding area method def area(self): print("Area of the Triangle is : ", (self.width*self.height)/2) rectangle = Rectangle(10, 20) triangle = Triangle(2, 10) rectangle.area() triangle.area()
Output:
Area of the Rectangle is : 200 Area of the Triangle is : 10.0
57访问 Child 类中的私有成员
class Human(): # Private var __privateVar = "this is __private variable" # Constructor method def __init__(self): self.className = "Human class constructor" self.__privateVar = "this is redefined __private variable" # Public method def showName(self, name): self.name = name return self.__privateVar + " " + name # Private method def __privateMethod(self): return "Private method" # Public method that returns a private variable def showPrivate(self): return self.__privateMethod() def showProtecded(self): return self._protectedMethod() class Male(Human): def showClassName(self): return "Male" def showPrivate(self): return self.__privateMethod() def showProtected(self): return self._protectedMethod() class Female(Human): def showClassName(self): return "Female" def showPrivate(self): return self.__privateMethod() human = Human() print(human.className) print(human.showName("Vasya")) print(human.showPrivate()) male = Male() print(male.className) print(male.showClassName()) female = Female() print(female.className) print(female.showClassName())
Output:
Human class constructor this is redefined __private variable Vasya Private method Human class constructor Male Human class constructor Female
58Python 中的抽象类
from abc import ABC, abstractmethod class AbstractClass(ABC): def __init__(self, value): self.value = value super().__init__() @abstractmethod def eat(self): pass class Parents(AbstractClass): def eat(self): return "Eat solid food " + str(self.value) + " times each day." class Babies(AbstractClass): def eat(self): return "Milk only " + str(self.value) + " times or more each day." food = 3 adult = Parents(food) print('Adult') print(adult.eat()) infant = Babies(food) print('Infants') print(infant.eat())
Output:
Adult Eat solid food 3 times each day. Infants Milk only 3 times or more each day.
59创建一个抽象类来覆盖 Python 中的默认构造函数
from abc import ABCMeta, abstractmethod class AbstractClass(object, metaclass=ABCMeta): @abstractmethod def __init__(self, n): self.n = n class Employee(AbstractClass): def __init__(self, salary, name): self.salary = salary self.name = name emp1 = Employee(10000, "John Doe") print(emp1.salary) print(emp1.name)
Output:
10000 John Doe
60使一个抽象类继承另一个抽象类
from abc import ABC, abstractmethod class A(ABC): def __init__(self, username): self.username = username super().__init__() @abstractmethod def name(self): pass class B(A): @abstractmethod def age(self): pass class C(B): def name(self): print(self.username) def age(self): return c = C('Test1234') c.name()
Output:
Test1234
61Python 中的 super 是做什么的
class A(object): def __init__(self, profession): print(profession) class B(A): def __init__(self): print('John Doe') super().__init__('Developer') b = B()
Output:
John Doe Developer
62super() 如何在多重继承中与 init() 方法一起工作
class F: def __init__(self): print('F%s' % super().__init__) super().__init__() class G: def __init__(self): print('G%s' % super().__init__) super().__init__() class H: def __init__(self): print('H%s' % super().__init__) super().__init__() class E(G, H): def __init__(self): print('E%s' % super().__init__) super().__init__() class D(E, F): def __init__(self): print('D%s' % super().__init__) super().__init__() class C(E, G): def __init__(self): print('C%s' % super().__init__) super().__init__() class B(C, H): def __init__(self): print('B%s' % super().__init__) super().__init__() class A(D, B, E): def __init__(self): print('A%s' % super().__init__) super().__init__() a = A() print(a)
Output:
A bound method D.__init__ of __main__.A object at 0x000000000369CFD0 D bound method B.__init__ of __main__.A object at 0x000000000369CFD0 B bound method C.__init__ of __main__.A object at 0x000000000369CFD0 C bound method E.__init__ of __main__.A object at 0x000000000369CFD0 E bound method G.__init__ of __main__.A object at 0x000000000369CFD0 G bound method H.__init__ of __main__.A object at 0x000000000369CFD0 H bound method F.__init__ of __main__.A object at 0x000000000369CFD0 F method-wrapper '__init__' of A object at 0x000000000369CFD0 __main__.A object at 0x000000000369CFD0
63将 super 与类方法一起使用
class A(object): @classmethod def name(self, employee): print('Employee Name: ', employee) class B(A): @classmethod def name(self, employee): super(B, self).name(employee) B.name('John Doe')
Output:
Employee Name: John Doe
64mro 是做什么的
class A(object): def dothis(self): print('From A class') class B1(A): def dothis(self): print('From B1 class') pass class B2(object): def dothis(self): print('From B2 class') pass class B3(A): def dothis(self): print('From B3 class') # Diamond inheritance class D1(B1, B3): pass class D2(B1, B2): pass d1_instance = D1() d1_instance.dothis() print(D1.__mro__) d2_instance = D2() d2_instance.dothis() print(D2.__mro__)
Output:
From B1 class (class '__main__.D1', class '__main__.B1', ) From B1 class (class '__main__.D2', class '__main__.B1', , class '__main__.B2', class 'object')
65Python 中的元类是什么
def _addMethod(fldName, clsName, verb, methodMaker, dict): compiledName = _getCompiledName(fldName, clsName) methodName = _getMethodName(fldName, verb) dict[methodName] = methodMaker(compiledName) def _getCompiledName(fldName, clsName): if fldName[:2] == "__" and fldName[-2:] != "__": return "_%s%s" % (clsName, fldName) else: return fldName def _getMethodName(fldName, verb): s = fldName.lstrip("_") return verb + s.capitalize() def _makeGetter(compiledName): return lambda self: self.__dict__[compiledName] def _makeSetter(compiledName): return lambda self, value: setattr(self, compiledName, value) class Accessors(type): def __new__(cls, clsName, bases, dict): for fldName in dict.get("_READ", []) + dict.get("_READ_WRITE", []): _addMethod(fldName, clsName, "get", _makeGetter, dict) for fldName in dict.get("_WRITE", []) + dict.get("_READ_WRITE", []): _addMethod(fldName, clsName, "set", _makeSetter, dict) return type.__new__(cls, clsName, bases, dict) class Employee(object, metaclass=Accessors): _READ_WRITE = ['name', 'salary', 'title', 'bonus'] def __init__(self, name, salary, title, bonus=0): self.name = name self.salary = salary self.title = title self.bonus = bonus b = Employee('John Doe', 25000, 'Developer', 5000) print('Name:', b.getName()) print('Salary:', b.getSalary()) print('Title:', b.getTitle()) print('Bonus:', b.getBonus())
Output:
Name: John Doe Salary: 25000 Title: Developer Bonus: 5000
66元类的具体案例
class UpperAttrNameMetaClass(type): def __new__(cls, clsname, bases, attrdict, *args, **kwargs): print('1. Create a new type, from ' + ' UpperAttrNameMetaClass.__new__') new_attrs = dict() for attr, value in attrdict.items(): if not callable(value) and not str(attr).startswith('__'): new_attrs[attr.upper()] = value else: new_attrs[attr] = value cls_obj = super().__new__(cls, clsname, bases, new_attrs, *args, **kwargs) return cls_obj def __init__(self, clsname, bases, attrdict): self.test = 'test' super().__init__(clsname, bases, attrdict) print('2. Initialize new type, increase test attribute,' + 'from UpperAttrNameMetaClass.__init__') def __call__(self, *args, **kwargs): print('3. Instantiate the new class,' + ' from UpperAttrNameMetaClass.__call__') new_obj = self.__new__(self, *args, **kwargs) new_obj.__init__(*args, **kwargs) return new_obj class ObjectNoInitMetaClass(type): def __call__(cls, *args, **kwargs): if len(args): raise TypeError('Must use keyword argument ' + ' for key function') new_obj = cls.__new__(cls) for k, v in kwargs.items(): setattr(new_obj, k.upper(), v) return new_obj class Pig(object, metaclass=UpperAttrNameMetaClass): size = 'Big' def __new__(cls, *args, **kwargs): print('4. Call __new__ in the __call__ of the metaclass,' + ' from Pig.__new__') obj = object.__new__(cls) return obj def __init__(self): print('5. After the new object is instantiated in ' + 'the __call__ of the metaclass,the object is promoted,' + ' from Pig.__init__') self.name = 'Mark' def talk(self): print(self.name) Pig().talk() print(Pig.__dict__) print(Pig.SIZE) class AnyOne(metaclass=ObjectNoInitMetaClass): pass foo = AnyOne(name='John', age=28) print(foo.NAME, foo.AGE) print(foo.__dict__)
Output:
1. Create a new type, from UpperAttrNameMetaClass.__new__ 2. Initialize new type, increase test attribute,from UpperAttrNameMetaClass.__init__ 3. Instantiate the new class, from UpperAttrNameMetaClass.__call__ 4. Call __new__ in the __call__ of the metaclass, from Pig.__new__ 5. After the new object is instantiated in the __call__ of the metaclass,the object is promoted, from Pig.__init__ Mark {'__doc__': None, 'test': 'test', '__weakref__': , 'SIZE': 'Big', '__init__': , '__dict__': , '__module__': '__main__', '__new__': , 'talk': } Big John 28 {'AGE': 28, 'NAME': 'John'}
67在 Python 中使用元类的单例类
class SingleInstanceMetaClass(type): def __init__(self, name, bases, dic): self.__single_instance = None super().__init__(name, bases, dic) def __call__(cls, *args, **kwargs): if cls.__single_instance: return cls.__single_instance single_obj = cls.__new__(cls) single_obj.__init__(*args, **kwargs) cls.__single_instance = single_obj return single_obj class Setting(metaclass=SingleInstanceMetaClass): def __init__(self): self.db = 'MySQL' self.port = 3306 bar1 = Setting() bar2 = Setting() print(bar1 is bar2) print(bar1.db, bar1.port) bar1.db = 'ORACLE' print(bar2.db, bar2.port)
Output:
True MySQL 3306 ORACLE 3306
68@staticmethod 和 @classmethod 有什么区别
class Employee: @classmethod def classmthd(*args): return args @staticmethod def staticmthd(*args): return args print(Employee.classmthd()) print(Employee.classmthd('test')) print(Employee.staticmthd()) print(Employee.staticmthd('test'))
Output:
(class '__main__.Employee',) (class '__main__.Employee', 'test') () ('test',)
69Python 中的装饰器是什么
def message(param1, param2): def wrapper(wrapped): class WrappedClass(wrapped): def __init__(self): self.param1 = param1 self.param2 = param2 super(WrappedClass, self).__init__() def get_message(self): return "message %s %s" % (self.param1, self.param2) return WrappedClass return wrapper @message("param1", "param2") class Pizza(object): def __init__(self): pass pizza_with_message = Pizza() print(pizza_with_message.get_message())
Output:
message param1 param2
70制作函数装饰器链
def benchmark(func): """ A decorator that prints the time a function takes to execute. """ import time def wrapper(*args, **kwargs): t = time.clock() res = func(*args, **kwargs) print("{0} {1}".format(func.__name__, time.clock()-t)) return res return wrapper def logging(func): """ A decorator that logs the activity of the script. (it actually just prints it, but it could be logging!) """ def wrapper(*args, **kwargs): res = func(*args, **kwargs) print("{0} {1} {2}".format(func.__name__, args, kwargs)) return res return wrapper def counter(func): """ A decorator that counts and prints the number of times a function has been executed """ def wrapper(*args, **kwargs): wrapper.count = wrapper.count + 1 res = func(*args, **kwargs) print("{0} has been used: {1}x".format(func.__name__, wrapper.count)) return res wrapper.count = 0 return wrapper @counter @benchmark @logging def letter_range(start, stop, step=1): start = ord(start.lower()) stop = ord(stop.lower()) for str_lst in range(start, stop, step): yield chr(str_lst) print(list(letter_range("a", "f"))) print('\n') print(list(letter_range("m", "z", 2)))
Output:
letter_range ('a', 'f') {} wrapper 0.0009437184107374183 wrapper has been used: 1x ['a', 'b', 'c', 'd', 'e'] letter_range ('m', 'z', 2) {} wrapper 3.131164480070134e-05 wrapper has been used: 2x ['m', 'o', 'q', 's', 'u', 'w', 'y']