No.22 & constraint reflection

No.22

Overview Today

  • operation
    • Stack
    • Sequential search
  • Iterables
  • Abnormal constraints +
  • reflection

Content Details

1. Job

# 看代码写结果
class Foo(object):

    def __init__(self, age):
        self.age = age

    def display(self):
        print(self.age)

data_list = [Foo(8), Foo(9)]
for item in data_list:
    print(item.age, item.display()) 
# 看代码写结果
class Base(object):
    def __init__(self,a1):
        self.a1 = a1

    def f2(self,arg):
        print(self.a1,arg)

class Foo(Base):
    def f2(self,arg):
        print('666')

obj_list = [Base(1),Foo(2),Foo(3)]
for obj in obj_list:
 item.f2()
# 看代码写结果
class StarkConfig(object):

    def __init__(self,num):
        self.num = num

    def changelist(self,request):
        print(self.num,request)

class RoleConfig(StarkConfig):

    def changelist(self,request):
        print('666')

config_obj_list = [StarkConfig(1),StarkConfig(2),RoleConfig(3)]
for item in config_obj_list:
    print(item.num)
# 看代码写结果
class StarkConfig(object):

    def __init__(self,num):
        self.num = num

    def changelist(self,request):
        print(self.num,request)

class RoleConfig(StarkConfig):

    def changelist(self,request):
        print(666,self.num)

config_obj_list = [StarkConfig(1),StarkConfig(2),RoleConfig(3)]
for item in config_obj_list:
    item.changelist(168)
# 看代码写结果
class StarkConfig(object):

    def __init__(self,num):
        self.num = num

    def changelist(self,request):
        print(self.num,request)

    def run(self):
        self.changelist(999)

class RoleConfig(StarkConfig):

    def changelist(self,request):
        print(666,self.num)

config_obj_list = [StarkConfig(1),StarkConfig(2),RoleConfig(3)]
config_obj_list[1].run()
config_obj_list[2].run()
# 看代码写结果
class UserInfo(object):
    pass

class Department(object):
    pass

class StarkConfig(object):

    def __init__(self,num):
        self.num = num

    def changelist(self,request):
        print(self.num,request)

    def run(self):
        self.changelist(999)

class RoleConfig(StarkConfig):

    def changelist(self,request):
        print(666,self.num)

class AdminSite(object):
    def __init__(self):
        self._registry = {}

    def register(self,k,v):
        self._registry[k] = v(k)

site = AdminSite()
site.register(UserInfo,StarkConfig)
site.register(Department,StarkConfig)
print(len(site._registry))
for k,row in site._registry.items():
    row.run()
# 看代码写结果
class Base(object):
    def __init__(self,name):
        self.name = name

class Foo(Base):
    def __init__(self,name):
        super().__init__(name)
        self.name = "于大爷"

obj1 = Foo('alex')
print(obj1.name)

obj2 = Base('alex')
print(obj2.name)
# 补全代码
class Context:
    pass

with Context() as ctx:
    ctx.do_something()

1.1 code is executed from top to bottom

print('你好')

def func():
    pass

func()
class Foo:
    x = 1        # 类的内部代码在解释期间就会执行
    def func(self):
        pass
Foo.x
class Foo:
    print('你好')  # 会打印
    def func(self):
        pass
# 类的内部代码在解释期间就会执行,函数和方法的内部代码在解释期间不会执行。
# 类的嵌套
class Foo:
    print('你')      # 会打印
    x = 1 
    
    def func(self):
        pass
    
    class Meta:
        print('好')   # 会打印
        y = 2
        def show(self):
            pass

1.2 Stack

class Stack(object):
    '''
    栈:后进先出
    '''
    def __init__(self):
        self.data_list = []

    def push(self, val):
        '''
        入栈:向栈中压入一个数据
        '''
        self.data_list.append(val)

    def pop(self):
        '''
        出栈:从栈中拿走一个数据
        '''
        return self.data_list.pop() if len(self.data_list) > 0 else 666

obj = Stack()
obj.push('alex')
obj.push('武沛齐')
obj.push('金老板')
print(obj.data_list)
v1 = obj.pop()
print(v1)
v2 = obj.pop()
print(v2)
v3 = obj.pop()
print(v3)
v4 = obj.pop()
print(v4)

2. iterables

Appearance: for loop can be an object can be called iterables.

class Foo:
    pass

obj = Foo()

How to make an object become iterable?

Implemented in a class __iter__method and returns an iterator or generator

class Foo:
    def __iter__(self):
        return iter([1,2,3,4])
        # v = [1,2,3]
        # return v.__iter__()               
obj = Foo()

class Foo:
    def __iter__(self):
        yield 1
        yield 2
        yield 3
obj = Foo()

for item in obj:
    print(item)

Remember: An object can be for as long as the loop, went to see where iter method of the object class in.

3. Constraints

#约束子类中必须写上send方法,如果不写则调用该方法时就会抛出NotImplementedError异常(子类没有实现指定方法所报的异常)。
class Interface(object):
    def send(self):
        raise NotImplementedError()

class Message(Interface):
    def send(self):
        print('发送短信')

class Email(Interface):
    def send(self):
        print('发送邮件')
class Message(object):
    def msg(self):
        print('发短信')
    def email(self):
        print('发邮件')
    def wechat(self):
        print('发微信')
        
obj = Message()
obj.msg()
obj.email()
obj.wechat()
class BaseMessage(object):
    def send(self, a1):
        raise NotImplementedError('子类中必须有send方法')

class Message(BaseMessage):
    def send(self):
        pass
     
class Email(BaseMessage):
    def send(self):
        pass
         
class Wechat(BaseMessage):
    def send(self):
        pass
    
class DingDing(BaseMessage):
    def send(self):
        pass
     
obj = Message()
obj.send()

4. reflection

According to a string to an object in the operation of its members.

  • getattr (object character string) → according to an object acquires a string object members.

    class Foo(object):
        def __init__(self, name):
            self.name = name    
        def login(self):
            pass
        def register(self):
            pass
    
    obj = Foo('alex')
    # 获取变量
    val = getattr(obj, 'name') 
    # 获取方法
    method_name = getter(obj, 'login') # 相当于是obj.login
    method_name()
  • the hasattr (Object, String) → according to an object in a string determines whether the member.

    from wsgiref.simple_server import make_server
    class View(object):
        def login(self):
            return '登陆'
    
        def logout(self):
            return '退出'
    
        def index(self):
            return '首页'
    
    def func(environ, start_response): # environ是个字典
        start_response('200 OK', [('Content-Type', 'text/plain; charset = utf-8')])
        obj = View()
        # 获取用户输入的URL
        method_name = environ.get('PATH_INFO').strip('/')
        if not hasattr(obj, method_name):
            return [''.encode('utf-8')]
        response = getattr(obj, method_name)()
        return [response.encode('uff-8')]
    
    # 作用:写一个网站,用户只要来访问,就会自动找到第三个参数并执行。
    server = make_server('192.168.12.88', 8000, func)
    server.server_forever()    
  • setattr (objects, strings, value) → member provided to an object in accordance with a string.

    class Foo():
        pass
    
    obj = Foo()
    setattr(obj, 'num', 666) # 等价于 obj.num = 666
    print(obj.num)
  • delattr (objects, strings) → based on a string to an object is deleted members.

    class Foo():
        pass
    
    obj = Foo()
    obj.num = 666
    delattr(obj, 'num')
    print(obj.num)

Examples

class Foo(object):
    def __init__(self, name):
        self.name = name
        
obj = Foo('alex')

# val = obj.name 取值  注意:name本是变量
val = getattr(obj, 'name') 

# obj.name = 'eric' 赋值
setattr(obj, 'name', 'eric')

# 注意:name是对象中的变量,函数参数'name'是字符串。调用此函数要将对象中的变量名用字符串写入参数,进行取值或赋值操作。        
class Foo(object):
    def login(self):
        pass
    def register(self):
        pass
    
obj = Foo()
func_name = input('请输入方法名:') # login
getattr(obj, func_name)()  # 用户输入功能名,就直接执行该方法。

'''
obj.login()
method_name = getter(obj, 'login') # 相当于是obj.login
method_name()

obj.register()
method_name = getter(obj, 'register')
method_name()
'''

Everything in Python objects

Internal members want to target operations can be achieved through mechanisms reflected by a string.

  • py file
  • package
  • class
  • Objects
# 模块learn.py:
num = 666
def func()
    print(888)    
class Foo:
    name = 'alex'
    def f1(self):
        print('f1')
        
# 正在执行的.py文件:
import learn

v1 = getattr(learn, 'num')  # learn.num
v2 = getattr(learn, 'func')
v2()                        # learn.func()

v3 = getattr(learn, 'Foo')  # learn.Foo
v4 = getattr(v3, 'name')    # learn.Foo.name

v5 = getattr(v3(), 'f1')    # learn.Foo().f1

5. Module: importlib

The module introduced in the form of a string.

import importlib
模块 = importlib.import_mdule('包.模块')

path = 'utils.redis.func'
import importlib

module_path, func_name = path.rsplit('.', 1)
module_object = importlib.import_module(module_path)

getattr(module_object, func_name)()

Guess you like

Origin www.cnblogs.com/elliottwave/p/12524791.html