类相关
@property
class User: __key = 'abc' # 只能在类内调用 def __init__(self,name, password): self.name = name self.__passwd = password # 只能在类内调用 @property def passwd(self): return self.__passwd @passwd.setter def passwd(self, value): # obj.passwd = xxx 的时候执行 self.__passwd = value @passwd.deleter def passwd(self): # del obj.passwd 时候执行 self.__passwd = 0
user = User('lee', 123456)
# print(user.__passwd) 无法调用
print(user.passwd) # @property
user.passwd=1234 # @passwd.setter
print(user.passwd)
del user.passwd # @passwd.deleter
print(user.passwd)
@classmethod
class ClassMethod: age = 1 def __init__(self, name): self.name = name @classmethod def tell(cls): print('类方法') print(cls) print(cls.age) a =ClassMethod('lee') ClassMethod.tell()
@staticmethod
class StaticMethod: age = 1 def __init__(self, name): self.name = name @staticmethod def tell(a, b): print(a, b) a = StaticMethod('lee') a.tell('165', '18') # 165 18 StaticMethod.tell('165', '18') # 165 18
自省
class User: age = 18 def __init__(self, name): self.name = name def tell(self): return '请给我打钱' def set_age(self, x): self.age = x lee = User('lee') # hasattr(obj,name) hasattr(lee, 'age') # True hasattr(lee, 'tell') # True hasattr(lee, 'height') # False # getattr(obj,name) getattr(lee,'age') # 18 t = getattr(lee,'tell') print(t()) # 请给我打钱 # setattr(obj, name, value) print(lee.age) # 18 setattr(lee, 'age', 19) print(lee.age) # 19 # delattr(obj, name) delattr(lee, 'age') # lee.age(10) # AttributeError: age
反射当前模块
import sys this_module = sys.modules[__name__] print(hasattr(this_module, 'User')) # True