day31 Pyhton 总结

# 什么是封装?    
  # 广义上(大家认为的) :        
    # 把一类事务的相同的行为和属性归到一个类中
# class Dog:
#     def bite(self):pass    
    # 狭义上(学术上的定论) :        
      # 把一些特殊的属性和方法藏在类中        
      # 外部无法调用,只有内部可以调用

# 类的命名空间(类的对象共享的资源) :
    # 静态属性
    # 类方法
    # 静态方法
    # 普通方法
    # property方法
# 对象的命名空间(对象独有的资源):
    # 对象的属性
    # 对象的方法
# 狭义上
    # 私有成员
    # 在类的内部 __成员名
    # 在类的外部 不能用
    # 在存储的空间中 _类名__成员名
# 1.私有成员不能在类的外部使用,也不能被继承
# 无论在哪个类中调用私有成员,一定是在哪个类调,就用哪个类的
class Foo(object):
    def __init__(self):
        self.__func()    # _Foo__func
        self.func()
    def __func(self):print('in Foo __func')  # _Foo__func
    def func(self):print('in Foo func')

class Son(Foo):
    def __func(self):print('in Son __func')   # _Son__func
    def func(self):print('in Son func')
Son()#in Foo __func  in Son func
# 2.类中的三个装饰器方法
# 先实现功能
# 某个方法如果用到self 传self
# 某个方法如果没用到self,用到类 传cls ,加@classmethod装饰器      *****
# 某个方法如果没用到self,没用到类  啥也不传,加@staticmethod装饰器
# 但凡是不需要传self参数的,都不需要实例化,直接使用类调用就可以了
# @property : 伪装一个方法成为一个属性,调用的时候不需要加()
# 3.反射 非常重要
# a.b这样的情况
# 如果由于某种原因,b变成了 'b'
# 那么就是用getattr(a,'b')的形式获取b对应的值
# 如果b是一个值 那么getattr的结果就是值
# 如果b是一个地址 那么getattr的结果就是地址,地址()就是执行
# from sys import modules
# getattr(modules[__name__],'全局变量名')
# 从当前文件中寻找全局变量对应的值/地址
from sys import modules
a = 2
b = 4
print(getattr(modules[__name__],'c',123))#123
# 有一个文件,有很多变量,也有很多函数,但是没有类
# 用户输入input任意的变量名或者函数名,
# 如果是变量 直接打印  - 用到一个内置函数
# 如果是函数 直接调用  - 用到一个内置函数
# 要求程序不报错
import sys
a='普通变量a'
b='普通变量b'
A='普通常量A'
B='普通常量B'
def f1():
    print('f1 function')
def f2():
    print('f2 function')
def f3():
    print('f3 function')
print(type(f3))
while 1:
    res = input('>>>:').strip()
    if res.upper() == 'Q':break
    if hasattr(sys.modules[__name__],res):
        obj = getattr(sys.modules[__name__],res)
        if callable(obj):
            obj()
        else:
            print(obj)
    else:
        print('error')
# 有一个类,有很多静态属性,也有很多静态方法/类方法
# 用户输入input任意的属性名或者方法名,
# 如果是属性 直接打印  - 用到一个内置函数
# 如果是方法 直接调用  - 用到一个内置函数
# 要求程序不报错
import sys
a='普通变量a'
b='普通变量b'
A='普通常量A'
B='普通常量B'
class fu:
    co='adc'
    print(type(co))
    @classmethod
    def f1(cls):
        print('f1 function')
    @staticmethod
    def f2():
        print('f2 function')
from types import MethodType
while 1:
    res = input('>>>:').strip()
    if res.upper() == 'Q':break
    if hasattr(fu,res):
        obj = getattr(fu,res)
        if isinstance(obj,MethodType):
            obj()
        else:
            print(obj)
    else:
        print('error')

猜你喜欢

转载自www.cnblogs.com/pythonz/p/10029971.html