当前位置: 首页 > 编程日记 > 正文

整理了 70 个 Python 面向对象编程案例,怎能不收藏?

985eb4fd705445f8169a591168758748.gif

作者 | 周萝卜

来源 | 萝卜大杂烩

Python 作为一门面向对象编程语言,常用的面向对象知识怎么能不清楚呢,今天就来分享一波

文章很长,高低要忍一下,如果忍不了,那就收藏吧,总会用到的

  • 在 Python 中创建一个类及其对象

  • 在 Python 中创建一个空类

  • 在 Python 中使用 Type 创建类

  • 在 Python 中创建和调用类的方法

  • 使用 __init__() 方法为数据属性赋值

  • 在 Python 中更新对象属性

  • 在 Python 中删除对象属性和对象

  • 在 Python 中检查和比较对象的类型

  • 在Python中将对象的所有属性复制到另一个对象

  • 在 Python 中迭代对象属性

  • 在 Python 中打印对象的所有属性

  • 在python中在运行时创建类的数据属性

  • 在函数中将对象的实例作为参数传递

  • 在 Python 中创建和使用自定义 Self 参数

  • 使用self参数来维护对象的状态

  • 在 Python 中创建和使用静态类变量

  • 在 Python 中的一个函数上使用多个装饰器

  • 在 Python 中的方法中同时访问 cls 和 self

  • 从装饰器访问实例方法的类

  • 使用给定的装饰器获取 Python 类的所有方法

  • 装饰一个 class

  • 将类字段作为参数传递给类方法上的装饰器

  • 在 Python 中创建多个传入参数列表的类变量

  • Python 中的 wraps 装饰器

  • 使用可选参数构建装饰器

  • 在 Python 中将参数传递给装饰器

  • @property 装饰器

  • 类和函数的装饰器

  • Python 中带参数和返回值的装饰器

  • Python 使用参数 wraps 装饰器

  • Python 装饰器获取类名

  • 简单装饰器示例

  • 在 Python 中使用 print() 打印类的实例

  • 在 Python 中的类中将装饰器定义为方法

  • 获取在 Python 中修饰的给定类的所有方法

  • 带参数和不带参数的 Python 装饰器

  • Python 中带有 self 参数的类方法装饰器

  • 在 Python 中的另一个类中使用隐藏的装饰器

  • 装饰器内部的 self 对象

  • 在 Python 中将多个装饰器应用于单个函数

  • Python 装饰器获取类实例

  • __init__ 和 __call__ 有什么区别

  • 在 Python 中使用 __new__ 和 __init__

  • Python 中的迭代重载方法

  • 在 Python 中使用迭代器反转字符串

  • Python 中 __reversed__ 魔术方法

  • Python 中的 __getitem__ 和 __setitem__

  • 在 Python 中使用 __getattr__ 和 __setattr__ 进行属性赋值

  • 什么是 __del__ 方法以及如何调用它

  • 创建类的私有成员

  • 一个 Python 封装的例子

  • 一个 Python 组合的例子

  • 一个Python聚合的例子

  • Python 中的单级、多级和多级继承

  • 在 Python 中获取一个类的父类

  • Python 中的多态性

  • 访问 Child 类中的私有成员

  • Python 中的抽象类

  • 创建一个抽象类来覆盖 Python 中的默认构造函数

  • 使一个抽象类继承另一个抽象类

  • Python 中的 super 是做什么的

  • super() 如何在多重继承中与 __init__() 方法一起工作

  • 将 super 与类方法一起使用

  • mro 是做什么的

  • Python 中的元类是什么

  • 元类的具体案例

  • 在 Python 中使用元类的单例类

  • @staticmethod 和 @classmethod 有什么区别

  • Python 中的装饰器是什么

  • 制作函数装饰器链

1在 Python 中创建一个类及其对象

class Employee:salary = 10000name = "John Doe"emp1 = Employee()
print(emp1.salary)
print(emp1.name)

Output:

10000
John Doe

2在 Python 中创建一个空类

class Employee:passe1 = Employee()
print(e1)e1.name = "John Doe"
print(e1.name)

Output:

<__main__.Employee object at 0x0000000002DA51D0>
John Doe

3在 Python 中使用 Type 创建类

e1 = type('Employee', (), {})()
print(e1)e1.name = "John Doe"
print(e1.name)

Output:

<__main__.Employee object at 0x0000000002DCC780>
John Doe

4在 Python 中创建和调用类的方法

class Employee:salary = 10000name = "John Doe"def tax(self):print(self.salary * 0.10)emp1 = Employee()
print(emp1.salary)
print(emp1.name)
emp1.tax()

Output:

10000
John Doe
1000.0

5使用 init() 方法为数据属性赋值

class Employee:def __init__(self, salary, name):self.salary = salaryself.name = nameemp1 = Employee(10000, "John Doe")
print(emp1.salary)
print(emp1.name)

Output:

10000
John Doe

6在 Python 中更新对象属性

class Employee:def __init__(self, salary, name):self.salary = salaryself.name = nameemp1 = Employee(10000, "John Doe")
print(emp1.salary)emp1.salary = 20000
print(emp1.salary)

Output:

10000
20000

7在 Python 中删除对象属性和对象

class Employee:def __init__(self, salary, name):self.salary = salaryself.name = nameemp1 = Employee(10000, "John Doe")del emp1.salary     # Delete object property
del emp1            # Delete object

Output:

哈哈

8在 Python 中检查和比较对象的类型

class Test(object):passprint(type(Test))obj1 = Test()
print(type(obj1))obj2 = Test()
print(type(obj1) is type(obj2))

Output:

< class 'type' >
< class '__main__.Test' >
True

9在Python中将对象的所有属性复制到另一个对象

class MyClass(object):def __init__(self):super(MyClass, self).__init__()self.foo = 1self.bar = 2obj1 = MyClass()
obj2 = MyClass()obj1.foo = 25
obj2.__dict__.update(obj1.__dict__)print(obj1.foo)
print(obj2.foo)

Output:

25
25

10在 Python 中迭代对象属性

class A():m = 1n = 2def __int__(self, x=1, y=2, z=3):self.x = xself._y = yself.__z__ = zdef xyz(self):print(x, y, z)obj = A()
print(dir(obj))
print([a for a in dir(obj) if not a.startswith('__')])

Output:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__int__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'm', 'n', 'xyz']
['m', 'n', 'xyz']

11在 Python 中打印对象的所有属性

class Animal(object):def __init__(self):self.eyes = 2self.name = 'Dog'self.color= 'Spotted'self.legs= 4self.age  = 10self.kids = 0animal = Animal()
animal.tail = 1temp = vars(animal)
for item in temp:print(item, ':', temp[item])

Output:

kids : 0
eyes : 2
name : Dog
color : Spotted
tail : 1
legs : 4
age : 10

12在python中在运行时创建类的数据属性

class Employee:passemp1 = Employee()
setattr(emp1, 'Salary', 12000)emp2 = Employee()
setattr(emp2, 'Age', 25)print(emp1.Salary)
print(emp2.Age)

Output:

12000
25

13在函数中将对象的实例作为参数传递

class Vehicle:def __init__(self):self.trucks = []def add_truck(self, truck):self.trucks.append(truck)class Truck:def __init__(self, color):self.color = colordef __repr__(self):return "{}".format(self.color)def main():v = Vehicle()for t in 'Red Blue Black'.split():t = Truck(t)v.add_truck(t)print(v.trucks)if __name__ == "__main__":main()

Output:

[Red, Blue, Black]

14在 Python 中创建和使用自定义 Self 参数

class Employee:def __init__(person, salary, name):person.salary = salaryperson.name = namedef print_details(emp):print(str(emp.salary) + ' : ' + emp.name)emp1 = Employee(10000, 'John Doe')
emp1.print_details()

Output:

10000 : John Doe

15使用self参数来维护对象的状态

class State(object):def __init__(self):self.field = 5.0def add(self, x):self.field += xdef mul(self, x):self.field *= xdef div(self, x):self.field /= xdef sub(self, x):self.field -= xs = State()
print(s.field)s.add(2)         # Self is implicitly passed.
print(s.field)s.mul(2)         # Self is implicitly passed.
print(s.field)s.div(2)         # Self is implicitly passed.
print(s.field)s.sub(2)         # Self is implicitly passed.
print(s.field)

Output:

5.0
7.0
14.0
7.0
5.0

16在 Python 中创建和使用静态类变量

class Employee:age = 25print(Employee.age)e = Employee()
print(e.age)e.age = 30
print(Employee.age)   # 25
print(e.age)          # 30

Output:

25
25
25
30

17在 Python 中的一个函数上使用多个装饰器

def my_decorator(func):def wrapper():print("Step - 1")func()print("Step - 3")return wrapperdef repeat(func):def wrapper():func()func()func()return wrapper@my_decorator
@repeat
def start_steps():print("Step - 2")start_steps()

Output:

Step - 1
Step - 2
Step - 2
Step - 2
Step - 3

18在 Python 中的方法中同时访问 cls 和 self

class MyClass:__var2 = 'var2'var3 = 'var3'def __init__(self):self.__var1 = 'var1'def normal_method(self):print(self.__var1)@classmethoddef class_method(cls):print(cls.__var2)def my_method(self):print(self.__var1)print(self.__var2)print(self.__class__.__var2)if __name__ == '__main__':print(MyClass.__dict__['var3'])clzz = MyClass()
clzz.my_method()

Output:

var3
var1
var2
var2

19从装饰器访问实例方法的类

class Decorator(object):def __init__(self, decoratee_enclosing_class):self.decoratee_enclosing_class = decoratee_enclosing_classdef __call__(self, original_func):def new_function(*args, **kwargs):print('decorating function in ', self.decoratee_enclosing_class)original_func(*args, **kwargs)return new_functionclass Bar(object):@Decorator('Bar')def foo(self):print('in foo')class Baz(object):@Decorator('Baz')def foo(self):print('in foo')print('before instantiating Bar()')
b = Bar()
print('calling b.foo()')
b.foo()

Output:

before instantiating Bar()
calling b.foo()
decorating function in  Bar
in foo

20使用给定的装饰器获取 Python 类的所有方法

import inspectdef deco(func):return funcdef deco2():def wrapper(func):passreturn wrapperclass Test(object):@decodef method(self):pass@deco2()def method2(self):passdef methodsWithDecorator(cls, decoratorName):sourcelines = inspect.getsourcelines(cls)[0]for i, line in enumerate(sourcelines):line = line.strip()if line.split('(')[0].strip() == '@' + decoratorName:  # leaving a bit outnextLine = sourcelines[i + 1]name = nextLine.split('def')[1].split('(')[0].strip()yield(name)print(list(methodsWithDecorator(Test, 'deco')))
print(list(methodsWithDecorator(Test, 'deco2')))

Output:

['method']
['method2']

21装饰一个 class

from functools import wrapsdef dec(msg='default'):def decorator(klass):old_foo = klass.foo@wraps(klass.foo)def decorated_foo(self, *args, **kwargs):print('@decorator pre %s' % msg)old_foo(self, *args, **kwargs)print('@decorator post %s' % msg)klass.foo = decorated_fooreturn klassreturn decorator@dec('foo decorator')
class Foo(object):def foo(self, *args, **kwargs):print('foo.foo()')@dec('subfoo decorator')
class SubFoo(Foo):def foo(self, *args, **kwargs):print('subfoo.foo() pre')super(SubFoo, self).foo(*args, **kwargs)print('subfoo.foo() post')@dec('subsubfoo decorator')
class SubSubFoo(SubFoo):def foo(self, *args, **kwargs):print('subsubfoo.foo() pre')super(SubSubFoo, self).foo(*args, **kwargs)print('subsubfoo.foo() post')SubSubFoo().foo()

Output:

@decorator pre subsubfoo decorator
subsubfoo.foo() pre
@decorator pre subfoo decorator
subfoo.foo() pre
@decorator pre foo decorator
foo.foo()
@decorator post foo decorator
subfoo.foo() post
@decorator post subfoo decorator
subsubfoo.foo() post
@decorator post subsubfoo decorator

22将类字段作为参数传递给类方法上的装饰器

import functools# imagine this is at some different place and cannot be changeddef check_authorization(some_attr, url):def decorator(func):@functools.wraps(func)def wrapper(*args, **kwargs):print(f"Welcome Message: '{url}'...")return func(*args, **kwargs)return wrapperreturn decorator# another dummy function to make the example workdef do_work():print("work is done...")def custom_check_authorization(some_attr):def decorator(func):# assuming this will be used only on this particular class@functools.wraps(func)def wrapper(self, *args, **kwargs):# get urlurl = self.url# decorate function with original decorator, pass urlreturn check_authorization(some_attr, url)(func)(self, *args, **kwargs)return wrapperreturn decoratorclass Client(object):def __init__(self, url):self.url = url@custom_check_authorization("some_attr")def get(self):do_work()# create object
client = Client('Hello World')# call decorated function
client.get()

Output:

Welcome Message: 'Hello World'...
work is done...

23在 Python 中创建多个传入参数列表的类变量

class Employee(object):def __init__(self, **kwargs):for key in kwargs:setattr(self, key, kwargs[key])emp = Employee(age=25, name="John Doe")
print(emp.age)
print(emp.name)

Output:

25
John Doe

24Python 中的 wraps 装饰器

from functools import wrapsdef decorator_func_with_args(arg1, arg2):def decorator(f):@wraps(f)def wrapper(*args, **kwargs):print("Before orginal function with decorator args:", arg1, arg2)result = f(*args, **kwargs)print("Ran after the orginal function")return resultreturn wrapperreturn decorator@decorator_func_with_args("test1", "test2")
def hello(name):"""A function which prints a greeting to the name provided."""print('Hello ', name)return 25print("Starting script..")
x = hello('John')
print("The value of x is:", x)
print("The wrapped functions docstring is:", hello.__doc__)
print("The wrapped functions name is:", hello.__name__)

Output:

Starting script..
Before orginal function with decorator args: test1 test2
Hello  John
Ran after the orginal function
The value of x is: 25
The wrapped functions docstring is: A function which prints a greeting to the name provided.The wrapped functions name is: hello

25使用可选参数构建装饰器

def d(arg):if callable(arg):  # Assumes optional argument isn't.def newfn():print('my default message')return arg()return newfnelse:def d2(fn):def newfn():print(arg)return fn()return newfnreturn d2@d('This is working')
def hello():print('hello world !')@d  # No explicit arguments will result in default message.
def hello2():print('hello2 world !')@d('Applying it twice')
@d('Would also work')
def hello3():print('hello3 world !')hello()
hello2()
hello3()

Output:

This is working
hello world !
my default message
hello2 world !
Applying it twice
Would also work
hello3 world !

26在 Python 中将参数传递给装饰器

def decorator_maker_with_arguments(decorator_arg1, decorator_arg2, decorator_arg3):def decorator(func):def wrapper(function_arg1, function_arg2, function_arg3):print("The wrapper can access all the variables\n""\t- from the decorator maker: {0} {1} {2}\n""\t- from the function call: {3} {4} {5}\n""and pass them to the decorated function".format(decorator_arg1, decorator_arg2, decorator_arg3,function_arg1, function_arg2, function_arg3))return func(function_arg1, function_arg2, function_arg3)return wrapperreturn decorator@decorator_maker_with_arguments("canada", "us", "brazil")
def decorated_function_with_arguments(function_arg1, function_arg2, function_arg3):print("This is the decorated function and it only knows about its arguments: {0}"" {1}" " {2}".format(function_arg1, function_arg2, function_arg3))decorated_function_with_arguments("france", "germany", "uk")

Output:

The wrapper can access all the variables- from the decorator maker: canada us brazil- from the function call: france germany uk
and pass them to the decorated function
This is the decorated function and it only knows about its arguments: france germany uk

27@property 装饰器

class Currency:def __init__(self, dollars, cents):self.total_cents = dollars * 100 + cents@propertydef dollars(self):return self.total_cents // 100@dollars.setterdef dollars(self, new_dollars):self.total_cents = 100 * new_dollars + self.cents@propertydef cents(self):return self.total_cents % 100@cents.setterdef cents(self, new_cents):self.total_cents = 100 * self.dollars + new_centscurrency = Currency(10, 20)
print(currency.dollars, currency.cents, currency.total_cents)currency.dollars += 5
print(currency.dollars, currency.cents, currency.total_cents)currency.cents += 15
print(currency.dollars, currency.cents, currency.total_cents)

Output:

10 20 1020
15 20 1520
15 35 1535

28类和函数的装饰器

from functools import wrapsdef decorator(func):@wraps(func)def wrapper(*args, **kwargs):print('sth to log: %s : %s' % (func.__name__, args))return func(*args, **kwargs)return wrapperclass Class_test(object):@decoratordef sum_func(self, a, b):print('class sum: %s' % (a + b))return a + bprint(Class_test.sum_func(1, 5, 16))

Output:

sth to log: sum_func : (1, 5, 16)
class sum: 21
21

29Python 中带参数和返回值的装饰器

def calculation(func):def wrapper(*args, **kwargs):print("Inside the calculation function")num_sum = func(*args, **kwargs)print("Before return from calculation function")return num_sumreturn wrapper@calculation
def addition(a, b):print("Inside the addition function")return a + bprint("Sum =", addition(5, 10))

Output:

Inside the calculation function
Inside the addition function
Before return from calculation function
Sum = 15

30Python 使用参数 wraps 装饰器

from functools import wrapsdef decorator_func_with_args(arg1, arg2):def decorator(f):@wraps(f)def wrapper(*args, **kwargs):print("Before orginal function with decorator args:", arg1, arg2)result = f(*args, **kwargs)print("Ran after the orginal function")return resultreturn wrapperreturn decorator@decorator_func_with_args("test1", "test2")
def hello(name):"""A function which prints a greeting to the name provided."""print('Hello ', name)return 25print("Starting script..")
x = hello('John')
print("The value of x is:", x)
print("The wrapped functions docstring is:", hello.__doc__)
print("The wrapped functions name is:", hello.__name__)

Output:

Starting script..
Before orginal function with decorator args: test1 test2
Hello  John
Ran after the orginal function
The value of x is: 25
The wrapped functions docstring is: A function which prints a greeting to the name provided.The wrapped functions name is: hello

31Python 装饰器获取类名

def print_name(*args):def _print_name(fn):def wrapper(*args, **kwargs):print('{}.{}'.format(fn.__module__, fn.__qualname__))return fn(*args, **kwargs)return wrapperreturn _print_nameclass A():@print_name()def a():print('Hi from A.a')@print_name()
def b():print('Hi from b')A.a()
b()

Output:

__main__.A.a
Hi from A.a
__main__.b
Hi from b

32简单装饰器示例

def my_decorator(func):def wrapper():print("Step - 1")func()print("Step - 3")return wrapper@my_decorator
def start_steps():print("Step - 2")start_steps()

Output:

Step - 1
Step - 2
Step - 3

33在 Python 中使用 print() 打印类的实例

class Element:def __init__(self, name, city, population):self.name = nameself.city = cityself.population = populationdef __str__(self):return str(self.__class__) + '\n' + '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))elem = Element('canada', 'tokyo', 321345)
print(elem)

Output:

name = canada
city = tokyo
population = 321345

34在 Python 中的类中将装饰器定义为方法

class myclass:def __init__(self):self.cnt = 0def counter(self, function):"""this method counts the number of runtime of a function"""def wrapper(**args):function(self, **args)self.cnt += 1print('Counter inside wrapper: ', self.cnt)return wrapperglobal counter_object
counter_object = myclass()@counter_object.counter
def somefunc(self):print("Somefunc called")somefunc()
print(counter_object.cnt)somefunc()
print(counter_object.cnt)somefunc()
print(counter_object.cnt)

Output:

Somefunc called
Counter inside wrapper:  1
1
Somefunc called
Counter inside wrapper:  2
2
Somefunc called
Counter inside wrapper:  3
3

35获取在 Python 中修饰的给定类的所有方法

class awesome(object):def __init__(self, method):self._method = methoddef __call__(self, obj, *args, **kwargs):return self._method(obj, *args, **kwargs)@classmethoddef methods(cls, subject):def g():for name in dir(subject):method = getattr(subject, name)if isinstance(method, awesome):yield name, methodreturn {name: method for name, method in g()}class Robot(object):@awesomedef think(self):return 0@awesomedef walk(self):return 0def irritate(self, other):return 0print(awesome.methods(Robot))

Output:

{'think': <__main__.awesome object at 0x00000213C052AAC0>, 'walk': <__main__.awesome object at 0x00000213C0E33FA0>}

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 wrapperif 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 wrapperclass Client(object):def __init__(self, url):self.url = url@check_authorizationdef 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@_decoratordef bar(self):print("Normal call")_decorator = staticmethod(_decorator)class TestB(TestA):@TestA._decoratordef 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 randomdef 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 wrapperclass MyHandler(object):@only_registered_usersdef 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_sumreturn wrapperdef addition(func):def wrapper(*args, **kwargs):num_sum = func(*args, **kwargs)print("Inside the addition function", num_sum)return num_sum + num_sumreturn wrapper@addition
@multiplication
def calculation(a):print("Inside the calculation function", a)return aprint("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 bufferdef read(self):pass  # read to buffer@staticmethoddef decorator(func):def func_wrap(cls, *args, **kwargs):cls.ser.write(func(cls, *args, **kwargs))return cls.ser.read()return func_wrapclass App():def __init__(self):self.ser = MySerial()@MySerial.decoratordef myfunc(self):self = 100return ['canada', 'australia']App().myfunc()

Output:

['canada', 'australia']

42initcall 有什么区别

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 中使用 newinit

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 = baseself.height = heightdef area(self):return (self.base * self.height) / 2class Square:def __init__(self, length):self.length = lengthdef area(self):return self.length*self.lengtha = 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 = lowself.high = highdef __iter__(self):return selfdef __next__(self):if self.current > self.high:raise StopIterationelse:self.current += 1return self.current - 1for num in Counter(5, 15):print(num)

Output:

5
6
..
..
15

45在 Python 中使用迭代器反转字符串

class Reverse:def __init__(self, data):self.data = dataself.index = len(data)def __iter__(self):return selfdef __next__(self):if self.index == 0:raise StopIterationself.index = self.index - 1return 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 = startself.end = endself.current = Nonedef __iter__(self):self.current = self.startwhile self.current < self.end:yield self.currentself.current += 1def __next__(self):if self.current is None:self.current = self.startif self.current > self.end:raise StopIterationelse:self.current += 1return self.current-1def __reversed__(self):self.current = self.endwhile self.current >= self.start:yield self.currentself.current -= 1obj1 = 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 中的 getitemsetitem

class Counter(object):def __init__(self, floors):self._floors = [None]*floorsdef __setitem__(self, floor_number, data):self._floors[floor_number] = datadef __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 中使用 getattrsetattr 进行属性赋值

class Employee(object):def __init__(self, data):super().__setattr__('data', dict())self.data = datadef __getattr__(self, name):if name in self.data:return self.data[name]else:return 0def __setattr__(self, key, value):if key in self.data:self.data[key] = valueelse: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 = namedef 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 = 100public_var = 200def __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 = Nonedef __init__(self, name):self.__name = namedef get_name(self):return self.__namepobj = Encapsulation('Rocky')
print(pobj.get_name())

Output:

Rocky

52一个 Python 组合的例子

class Salary:def __init__(self, pay):self.pay = paydef get_total(self):return (self.pay*12)class Employee:def __init__(self, pay, bonus):self.pay = payself.bonus = bonusself.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 = paydef get_total(self):return (self.pay*12)class Employee:def __init__(self, pay, bonus):self.pay = payself.bonus = bonusdef 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 = 2018def 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 = Truename = '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 mattersprint('Name: {}'.format(self.name))mactower = MacTower()# Multilevel inheritence
class MusicalInstrument:num_of_major_keys = 12class StringInstrument(MusicalInstrument):type_of_wood = 'Tonewood'class Guitar(StringInstrument):def __init__(self):self.num_of_strings = 6print('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):passclass B(object):passclass C(A, B):passprint(C.__bases__)

Output:

(< class '__main__.A' >, < class '__main__.B' >)

56Python 中的多态性

# Creating a shape Class
class Shape:width = 0height = 0# Creating area methoddef area(self):print("Parent class Area ... ")# Creating a Rectangle Class
class Rectangle(Shape):def __init__(self, w, h):self.width = wself.height = h# Overridding area methoddef 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 = wself.height = h# Overridding area methoddef 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 methoddef __init__(self):self.className = "Human class constructor"self.__privateVar = "this is redefined __private variable"# Public methoddef showName(self, name):self.name = namereturn self.__privateVar + " " + name# Private methoddef __privateMethod(self):return "Private method"# Public method that returns a private variabledef 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, abstractmethodclass AbstractClass(ABC):def __init__(self, value):self.value = valuesuper().__init__()@abstractmethoddef eat(self):passclass 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, abstractmethodclass AbstractClass(object, metaclass=ABCMeta):@abstractmethoddef __init__(self, n):self.n = nclass Employee(AbstractClass):def __init__(self, salary, name):self.salary = salaryself.name = nameemp1 = Employee(10000, "John Doe")
print(emp1.salary)
print(emp1.name)

Output:

10000
John Doe

60使一个抽象类继承另一个抽象类

from abc import ABC, abstractmethodclass A(ABC):def __init__(self, username):self.username = usernamesuper().__init__()@abstractmethoddef name(self):passclass B(A):@abstractmethoddef age(self):passclass C(B):def name(self):print(self.username)def age(self):returnc = 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):@classmethoddef name(self, employee):print('Employee Name: ', employee)class B(A):@classmethoddef 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')passclass B2(object):def dothis(self):print('From B2 class')passclass B3(A):def dothis(self):print('From B3 class')# Diamond inheritance
class D1(B1, B3):passclass D2(B1, B2):passd1_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 fldNamedef _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 = nameself.salary = salaryself.title = titleself.bonus = bonusb = 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()] = valueelse:new_attrs[attr] = valuecls_obj = super().__new__(cls, clsname, bases, new_attrs,*args, **kwargs)return cls_objdef __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_objclass 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_objclass 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 objdef __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):passfoo = 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 = Nonesuper().__init__(name, bases, dic)def __call__(cls, *args, **kwargs):if cls.__single_instance:return cls.__single_instancesingle_obj = cls.__new__(cls)single_obj.__init__(*args, **kwargs)cls.__single_instance = single_objreturn single_objclass Setting(metaclass=SingleInstanceMetaClass):def __init__(self):self.db = 'MySQL'self.port = 3306bar1 = 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:@classmethoddef classmthd(*args):return args@staticmethoddef staticmthd(*args):return argsprint(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 = param1self.param2 = param2super(WrappedClass, self).__init__()def get_message(self):return "message %s %s" % (self.param1, self.param2)return WrappedClassreturn wrapper@message("param1", "param2")
class Pizza(object):def __init__(self):passpizza_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 takesto execute."""import timedef wrapper(*args, **kwargs):t = time.clock()res = func(*args, **kwargs)print("{0} {1}".format(func.__name__, time.clock()-t))return resreturn wrapperdef 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 resreturn wrapperdef counter(func):"""A decorator that counts and prints the number of times afunction has been executed"""def wrapper(*args, **kwargs):wrapper.count = wrapper.count + 1res = func(*args, **kwargs)print("{0} has been used: {1}x".format(func.__name__, wrapper.count))return reswrapper.count = 0return 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']

4afe3091b06eede385616d29d12f0cd0.gif

df5993302eb0be3dde4dec11f5164329.png

资讯

OpenAI真的open了,更加开放

资讯

Meta新语音模型可支持128种语言交流

资讯

Meta研发触觉手套助力元宇宙

专访

低代码平台产品的使用者都是谁?

27b0a4f32c98316dfaf54289f0efee33.png

分享

eb71fce02f9565ed796e1c8f6d86c242.png

点收藏

6530bb970733f8c55eeabdef0587914b.png

点点赞

18a3a3d23f5bb970874275cd5288f5bb.png

点在看

相关文章:

ionic中的ion-option-button

2019独角兽企业重金招聘Python工程师标准>>> 代码 <ion-option-button class"button-assertive" ng-click"df(itemData)">批准 </ion-option-button> 效果图 转载于:https://my.oschina.net/u/1416844/blog/465730

memset函数详细说明

1。void *memset(void *s,int c,size_t n)总的作用&#xff1a;将已开辟内存空间 s 的首 n 个字节的值设为值 c。2。例子#include <stdio.h>#include <string.h>void main(){char s[]"hello";memset(s,*,2);printf("%s",s);} 输出&#xff1a…

CES Asia专题|微鹅展示无线充电,智能手机的无线充电时代何时来临?

无线充电离商业化应用还有多远&#xff1f; 此前一直有传闻苹果在新一代iPhone上会推出无线充电&#xff0c;在CES Asia上&#xff0c;我们也看到了无线充电技术方案解决商微鹅带来的最新产品。 据了解&#xff0c;目前我们所说的无线充电其实是指近场无线充电&#xff0c;让充…

Linux下Socket编程

Linux下Socket编程 网络的Socket数据传输是一种特殊的I/O&#xff0c;Socket也是一种文件描述符。Socket也具有一个类似于打开文件的函数调用Socket()&#xff0c;该函数返回一个整型的Socket描述符&#xff0c;随后的连接建立、数据传输等操作都是通过该Socket实现的。 什么…

看大众点评如何通过实时监控系统CAT打造7*24服务

为什么80%的码农都做不了架构师&#xff1f;>>> 看大众点评如何通过实时监控系统CAT打造7*24服务 2015-06-08 尤勇 高可用架构 https://github.com/dianping/cat 本文根据尤勇在【QCon高可用架构群】中的分享内容整理而成。 尤勇是大众点评网资深工程师&#x…

Python 快速实现分列转到行!

作者 | 黄伟呢来源 | 数据分析与统计学之美之前看到一篇文章&#xff0c;用Excel快速实现分列转到行的操做。数据源大致是这样的&#xff1a;基于此&#xff0c;我动起了一个念头&#xff1a;看看如何用Python快速实现这个操作。数据源已经构造好&#xff0c;咱们开干&#xff…

javabean属性的类型选择包装类还是基本数据类型

学生 参加考试&#xff0c;需要在表中存放分数score字段 &#xff0c;score是采用double 还是Double &#xff1f; 假如有个同学张三 没有参加考试&#xff0c;double 默认值 0 &#xff0c; Double 默认值 null 使用原始类型&#xff0c;无法区分0值没有数据&#xff0c;还是值…

C语言实现的Web服务器

另一篇&#xff1a;标准C实现WEB服务器http://blog.sina.com.cn/s/blog_4b73e7600100b02c.html本文原文地址&#xff1a; http://blog.sina.com.cn/s/blog_4b73e760010007id.html自己研究了好几天终于写出来一个&#xff0c;哈哈&#xff0c;当然也从网上得到了很多的帮助拉。谢…

使用深度学习检测混凝土结构中的表面裂缝

作者 | 小白来源 | 小白学视觉混凝土建筑裂缝介绍表面裂缝检测是监测混凝土结构健康的一项重要任务。如果裂纹发展并继续扩展&#xff0c;它们会减少有效承载表面积&#xff0c;并且随着时间的推移会导致结构失效。裂纹检测的人工过程费时费力&#xff0c;且受检验人员主观判断…

Python学习笔记--序列

Sequence序列 1.序列操作 seq[ind1:ind2] seq[ind] seq1 seq2 seq1 * seq2 seq * n obj in seq obj not in seq 2.切片操作 #反转操作 seq[::-1] #隔一个取一个 seq[::2] #取全部 seq[:None] ##序列类型可用的内建函数 enumerate(seq) #接受一个迭代对象&#xff0c;返回由索引…

「深度」线下大数据正成为构建精准“用户画像”的最大助力

不管是针对消费者的宣传还是营销&#xff0c;或者是针对公司的管理运营&#xff0c;大数据在其中的作用从本质来讲就是在构造“用户画像”。 近年来&#xff0c;在智能化趋势的推动下&#xff0c;社会经济的众多领域都发生了翻天覆地的变化&#xff0c;其中尤其以金融、零售等…

Android上成功实现了蓝牙的一些Profile

前段时间做蓝牙方面的开发&#xff0c;Google的Android只实现了Handset/Handfree和A2DP/AVRCP等Profile&#xff0c;而其 它常用的Profile如HID/DUN/SPP/OPP/FTP/PAN等却没有实现&#xff0c;并且Google方面关于何时实现也没有一个时间表。 前段时间我实现了HID/DUN/SPP三个Pro…

拥有「人类智能」的全球首款有「思想」的机器人,活细胞培养的神经元

出品 | AI科技大本营&#xff08;ID:rgznai100&#xff09; 脑机接口&#xff0c;其主体是人的大脑&#xff0c;利用人大脑中产生的信号转换为命令而执行任务。 首款有思想的机器人&#xff1f;是的&#xff0c;你真的没有看错&#xff01; 反过来说呢&#xff0c;比如主体是机…

使用VS2010调试技巧让C指针无处遁形

Linux 下调试远没有windows下的VS方便&#xff0c;不管是VC6还是VS2003&#xff0c;2005&#xff0c;2008&#xff0c;2010&#xff0c;2012. VS2012自动格式化代码 CtrlKD VS下调试一定要注意尽量不要用F11&#xff0c;要用F10&#xff01;不然需要引入库文件&#xff0c;提示…

Maven就是这么简单

2019独角兽企业重金招聘Python工程师标准>>> 什么是Maven Maven是一个采用纯Java编写的开源项目管理工具, Maven采用了一种被称之为Project Object Model (POM)概念来管理项目&#xff0c;所有的项目配置信息都被定义在一个叫做POM.xml的文件中.. **Maven是一款跨平…

C语言的内联函数的作用

关内联函数键字inline void myprintf(int a){priintf("%d",a);}int main(){for(i0;i<100;i)myprintf(3);}对于这个函数&#xff0c;在进行反复的打印3的过程中我们是不是要反复的调用myprintf(int a)这个函数&#xff0c;进函数和出函数是需要时间的&#xff0c;假…

推荐 2个十分好用的 pandas 数据探索分析神器!

作者 | 俊欣来源 | 关于数据分析与可视化今天小编给大家推荐两款超好用的工具来对数据进行探索分析。更好地帮助数据分析师从数据集当中来挖掘出有用的信息PandasGUI一听到这个名字&#xff0c;大家想必就会知道这个工具是在Pandas的基础之上加了GUI界面&#xff0c;它所具备的…

DoubleViewPager

https://github.com/eltld/DoubleViewPager https://github.com/eltld/DoubleViewPagerSample

OCQ亮相中国移动办公峰会 荣获2017中国移动办公创新品牌

11月21日至23日&#xff0c;由中国软件网主办的“新格局 再出发——企服三会”在北京中关村软件园国际会议中心隆重举行!国内市场上移动办公、CRM、HR三大领域的主流企业参加会议&#xff0c;百位业界专家学者汇聚一堂&#xff0c;交流经验&#xff0c;碰撞思维&#xff0c;对三…

typedef和define具体的详细区别

1) #define是预处理指令&#xff0c;在编译预处理时进行简单的替换&#xff0c;不作正确性检查&#xff0c;不关含义是否正确照样带入&#xff0c;只有在编译已被展开的源程序时才会发现可能的错误并报错。例如&#xff1a; #define PI 3.1415926 程序中的&#xff1a;areaPI*r…

IOS初级:NSKeyedArchiver

NSKeyedArchiver对象归档 首先要实现<NScoding>里面的两个代理方法initWithCoder,encodeWithCoder property (nonatomic, copy) NSString *keyName; /*将某个对象写入文件时候会调用在这个方法中说清楚哪些属性需要存储*/ - (void)encodeWithCoder:(NSCoder *)encoder{[e…

「摸鱼」神器来了,Python 实现人脸监测制作神器

作者 | 李秋键 出品 | AI科技大本营&#xff08;ID:rgznai100&#xff09; 最近都在讨论工作摸鱼&#xff0c;网易云音乐也出了合理摸鱼时间表&#xff0c;今天给大家推荐如何用python实现摸鱼~码住呦&#xff01; 引言&#xff1a;脸部表情是人类情绪的最直接外部表现之一和进…

初学Java——选择

1.boolean数据类型 1)取值为true/false 2)关系操作符的运算结果是boolean类型&#xff08;6种关系运算符同C语言&#xff09;2.分支语句 1)单分支if 2)双分支if-else 3)多分支if-else(此编码风格可避免深度缩进) if(){ } else if(){ } else if(){ } …

C语言宏定义使用技巧

写好C语言&#xff0c;漂亮的宏定义很重要&#xff0c;使用宏定义可以防止出错&#xff0c;提高可移植性&#xff0c;可读性&#xff0c;方便性等等。下面列举一些成熟软件中常用得宏定义。。。。。。1&#xff0c;防止一个头文件被重复包含#ifndef COMDEF_H#define COMDEF_H//…

java显示本地磁盘所有盘符,显示桌面路径

import java.io.File; import javax.swing.filechooser.FileSystemView;/** 显示本地磁盘根盘符&#xff0c;显示桌面路径 */ public class RDDemo {static File[] files;public static void main(String[] args) {FileSystemView sys FileSystemView.getFileSystemView();fil…

Twitter 禁止未经用户同意分享照片和视频

整理 | 禾木木 出品 | AI科技大本营&#xff08;ID:rgznai100&#xff09; Twitter 宣布将扩大私人信息政策&#xff0c;包括在未经个人许可的情况下共享的私人媒体&#xff0c;例如照片和视频&#xff0c;因为该社交媒体平台旨在改善用户隐私和安全。 “分享个人媒体&#xff…

这就是我向您推荐使用Thunderbird邮件客户端的理由

E-MAIL服务是最古老的互联网服务之一&#xff0c;相信很多人都在使用&#xff0c;只不过频率不同。IM出现后的&#xff08;及时通信工具&#xff09;一段时间&#xff0c;E-MAIL的通信不及时性估计让很多人交流会更倾向于IM。但是电子邮件&#xff08;E-MAIL&#xff09;仍然是…

ATT汇编语言与GCC内嵌汇编简介

AT&T汇编语言与GCC内嵌汇编简介1 AT&T 与INTEL的汇编语言语法的区别1.1大小写1.2操作数赋值方向1.3前缀1.4间接寻址语法1.5后缀1.6指令2 GCC内嵌汇编2.1简介2.2内嵌汇编举例2.3语法2.3.1汇编语句模板2.3.2输出部分2.3.3输入部分2.3.4限制字符2.3.5破坏描述部分2.4GCC如…

递归和迭代之间的差

递归的基本概念:编程技巧程序调用自身递归调用,是一个函数&#xff0c;调用自身. 在一个函数的定义直接或间接调用自己的方法,它通常是一个大的&#xff0c;复杂的问题分解成一个需要解决的问题类似于原来小问题,它可以大大减少的代码量.使用递归的能力是有限的语句来定义对象的…

智能交通:影响人类未来10-40年的重大变革

作者 | 百度创始人、董事长兼CEO李彦宏 《智能交通&#xff1a;影响人类未来10—40年的重大变革》&#xff0c;是我写的第三本关于人工智能的书。第一本是2017年编写的《智能革命&#xff1a;迎接人工智能时代的社会、经济与文化变革》&#xff0c;第二本是2020年编写的《智能…