Reflections on Python's Introduction

Keywords: Python Attribute

1. Reflection: (introspection)

Reflection mainly refers to the ability of a program to access, detect and modify its own state or behavior (introspection).

Reflection in Python Object Oriented: Operating the properties of an object in the form of strings. Everything in Python is an object (reflection can be used)

<1> getattr () acquisition
<2> setattr () settings
< 3 > hasattr () to determine whether there is
<4> Delattr () deleted

(1) Manipulating the attributes and methods of objects through strings

class A:
    def __init__(self,name):
        self.name = name

    def func(self):
        print("is A func")
a = A("rimo")


A.func()
print(a.name)
a.func()

(2) Reflection is used in the angle of the object

class A:
    def __init__(self,name):
        self.name = name

    def func(self):
        print("is A func")
a = A("rimo")

print(hasattr(a,"name"))  # Returning to True means that the name attribute exists in object a.

print(getattr(a,"name"))
f = getattr(a,"func")
f()
setattr(a,"age",18)
print(a.__dict__)

delattr(a,"name")
print(a.__dict__)

(3) Class Angle Use Reflection

class A:
    def __init__(self,name):
        self.name = name

    def func(self):
        print("is A func")

a = A("rimo")

print(hasattr(A,"name"))
f = getattr(A,"func")
f(11)

(4) Reflection is used in the current module

def func():
    print("is func")

# Current module:
print(globals()["func"])

import sys
o = sys.modules[__name__]   # Get the object corresponding to the current module name
f = getattr(o,"func")
f()

(5) Reflection is used in other modules

import test       # Import module
test.func()

o = globals()["test"]
getattr(o,"func")()

(6) Reflective application scenarios

class Blog:

    def login(self):
        print("is login")

    def register(self):
        print("is register")

    def comment(self):
        print("is comment")

    def log(self):
        print("is log")

    def log_out(self):
        print("is log_out")

b = Blog()

func_dic = {
    "1":b.login,
    "2":b.register,
    "3":b.comment,
    "4":b.log,
    "5":b.log_out
}

msg = """
1.Sign in
2.register
3.comment
4.Journal
5.Cancellation
"""

choose = input(msg)
if choose in func_dic:
    func_dic[choose]()
Modify the above code to reduce the code (manipulating object properties and methods through strings)
class Blog:
    def login(self):
        print("is login")

    def register(self):
        print("is register")

    def comment(self):
        print("is comment")

    def log(self):
        print("is log")

    def log_out(self):
        print("is log_out")

b = Blog()

msg = """
login
register
comment
log
log_out
"""

while 1:
    choose = input(msg)
    if hasattr(b,choose):
        getattr(b,choose)()
    else:
        print("Please re-enter!")

Posted by BlueNosE on Tue, 08 Oct 2019 13:09:17 -0700