Python about reflection and special member methods of classes

巴扎黑
Release: 2017-09-16 10:06:34
Original
1075 people have browsed it

This article will share with you Python's special member methods about reflection and classes. It is very good and has reference value. Friends who need it can refer to it

Reflection

Reflection means that there are 4 built-in functions: getattr, hasattr, setattr, delattr to get members, check members, set members, delete members


class Dog(object):
  def __init__(self,name):
    self.name = name
  def eat(self):
    print("%s is eating..."%self.name)
def run():
  print("runing ....")
d = Dog("lucy")
choise=input("请输入要调用的方法:")
if hasattr(d,choise):#判断一个对象是否有对应的字符串方法
  func=getattr(d,choise)#根据字符串去获取对象里相应的方法或属性的内存地址对象
  func()
else:
  setattr(d,choise,run)#setattr(obj,y,fun)相当于obj.y=fun,fun可以是属性或者方法
  v=getattr(d,choise)
  print(v)
Copy after login

dir([obj]):

Calling this method will return a list containing most of the attribute names of obj (there will be some special attributes that are not included). The default value of obj is the current module object.

hasattr(obj, attr):

This method is used to check whether obj has an attribute with a value named attr and returns a Boolean value.

getattr(obj, attr):

Calling this method will return the value of the attribute named attr value in obj, for example, if attr is 'bar ', then return obj.bar.

setattr(obj, attr, val):

Calling this method will assign val to the attribute named attr of obj. For example, if attr is 'bar', it is equivalent to obj.bar = val.

__doc__ View the detailed description information
__module__ represents the module in which the currently operated object is located
__class__ represents the class to which the currently operated object belongs
__init__ The constructor automatically creates objects through classes Execute the
__del__ destructor method, and the current object is released in the memory. Automatically kill the demon and execute
__call__. Add parentheses after the object to trigger execution.
__dict__View the members in the class or object.
__str__If If this method is defined in a class, then when printing such an object, the return value of this method is output.
__getitem__ When the attribute member of a dictionary is defined in the class, you can get the
__setitem__ setting to modify the dictionary in the class. Data
__delitem__Deletes the data of the dictionary in the class
__metalass__It is used to indicate who instantiates and creates the class
__new__ triggers __init__ to create an instance


from lib.ss import a
#示例类 dog
class doges(object):
  """类的描述信息"""
  def __init__(self,name,food):
    self.name=name
    self.food=food
    self.data={}#定义一个类的字典
  def __call__(self, *args, **kwargs):#对象后面加括号解执行
    print(*args)
  def __str__(self):#默认输出返回值
    return self.name
  def __getitem__(self):#可以获取类的的字典
    return self.data
  def __setitem__(self, key, value):#可以设置类的的字典
    self.data[key]=value
  def __delitem__(self, key):#可以删除类的字典的内容
    del self.data[key]
dog=doges('xxx','iii')
print(dog.__doc__)
b=a()
print(b.__module__)#操作的对象的那个模块
print(dog.__class__)#当前操作的对象的类是什么
dog('111')#
print(doges.__dict__)#查看类或对象的成员 类只打印类的成员不打印对象的成员
print(dog.__dict__)#查看类或对象的成员 对象只打印对象的成员不打印类的成员
print(dog)#打印 __str__的返回值
print(dog.__str__())#打印返回值
dog['1']=1000#触发.__setitem__()
dog['2']=1000#触发.__setitem__()
print(dog.__getitem__())
print(dog.__delitem__('1'))#删除类中字典
print(dog.__getitem__())
#设置类的特殊方法
def func(self):
  print('hello word%s'%self.name)
  print()
def __init__(self,name,age):
  self.name=name
  self.age=age
##type参数 1:类名 2.类的基类 3.类的成员,字典格式
CAT=type('CAT',(object,),{'func':func,'__init__':__init__})
cat=CAT('喵喵',3)
cat.func()
print(cat.name,cat.age)
Copy after login

The above is the detailed content of Python about reflection and special member methods of classes. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!