# getattr
# hasattr
# setattr
# delattr

class Foo:
    def __init__(self, name,age):
        self.name = name
        self.age = age
    def show(self):
        return  "%s-%s " %(self.name,self.age)
    def __int__(self):
        return 123
    def __str__(self):
        return 'uuu'
obj = Foo('pis', 18)

r = int(obj) # r = 123
u = str(obj)


# 通过字符串的形式操作对象中的成员

# func = getattr(obj, 'show')
# print(func)
# r = func()
# print(r)

 

# print(hasattr(obj, 'name'))

# setattr(obj, 'k1', 'v1')
# print(obj.k1)

# delattr(obj, 'name')
# obj.name

 

引入单例模式

class Foo:
    def __init__(self, name,age):
        self.name = name
        self.age = age

    def show(self):
        print(self.name,self.age)

v = None

while True:
    if v:
        v.show()
    else:
        v = Foo('pis', 123)
        v.show()

 

使用:

class Foo:

    __v = None

    @classmethod
    def get_instance(cls):
        if cls.__v:
            return cls.__v
        else:
            cls.__v = Foo()
            return cls.__v

obj1 = Foo.get_instance()
print(obj1)
obj2 = Foo.get_instance()
print(obj2)
obj3 = Foo.get_instance()
print(obj3)