Usage and understanding of hasattr ()--hasattr (obj, target)
Determines whether the object obj contains, targets the target property, and then returns a Boolean value that returns True if there is no return false.
>>> class School:... def __init__(self):... self.teacher_name = self.teacher... def teacher(self): ... return input("输入姓名:")... >>> s1 = School() #实例化一个学校对象>>> hasattr(s1, "teacher") #查看s对象中是否有teacher属性(方法)True #有该属性返回True>>> hasattr(s1, "student")False
Usage of getattr ()--getattr (obj, target)
Using the GetAttr () function, you can get the properties, methods in the object obj
>>> class School:... def __init__(self):... self.teacher_name = self.teacher... def teacher(self): ... return input("输入姓名:")... >>> s2 = School()>>> func = getattr(s2, "teacher") #获取s2实例当中的teacher函数,并将其赋值给func>>> print(func()) #在这儿调用func函数,等于调用teacher函数输入姓名: lina‘lina‘>>> >>> getattr(s2, "student") #尝试获取一个对象中不存在的方法Traceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: ‘School‘ object has no attribute ‘student‘
SetAttr () assigns a value to an object's property, and if the property does not exist, it is created first in the assignment--setattr (obj, name, value)
See here I think all can understand how to use, in the last example, we try to get a non-existent property error, if we first use the SetAttr () method, then you can first create the property, method in the object
>>> class School:... def __init__(self):... self.teacher_name = self.teacher... def teacher(self): ... return input("输入姓名:")... >>> >>> def student():... return input("学生姓名:")... >>> setattr(School, "student", student) #直接往School类当中设置名字为"student"的方法student也是可以的,>>>School.student() #现在在School类当中直接调用student()方法就不会报错了学生姓名:luna‘luna‘>>> s3 = School()>>> s3.__setattr__("stu", student) #类中的隐藏函数__setattr__(name, value) 也可以完成设置属性、方法>>> s3.stu()学生姓名:Amber‘Amber‘>>>
Hasattr (), GetAttr () Think and expand
Many times we face an unknown program, unknown class. Also can't go to blind change other people's code, and these two functions can help us to test, plus setattr () can be directly patched, to modify to achieve our purpose. The
and the more important applications of hasattr () and GetAttr () are, of course, relational mappings. The
knows that the way a class is associated with a class or between a function or an object is a combination of inheritance, derivation, and class. All of these methods need to be contacted directly.
and Hasattr (), and GetAttr () can help us reach a.a-------> b.b to build a relational mapping of two unrelated objects. Even create multilevel mappings randomly, C <-------A-----> B without affecting the function or class of the mapping.
As now we write a can be completed and user interaction, implementation of uploading, downloading, viewing the directory of the class, the specific business logic function will not be redundant write! The main view is to use Hanattr () and getattr () to interact, invoke the logical function
Import socketclass uploaddownload: "" This is a class with a remote server, send command to implement the upload download function _connect () Link remote server "" "Def __in it__ (self, IP, PORT): Self.ip = IP Self.port = PORT self.sock = Self._connect () #调用_connect () function link remote server self.commands = ["Upload", "Download", "directory"] def _connect (self): s = socket.socket (socket.af_inet, socket. Sock_stream) S.connect ((Self.ip, Self.port)) return S def _command (self): while True:p Rint ("Enter cmd like This:upload/home/user/lina/dance.mp4") #提示输入格式 cmd = input ("Enter cmd:"). Strip () #输入指定命令格式, and remove the space if not cmd:continue Else:cmds = Cmd.split (") #简单处理, divide the command and parameters Open if cmds[0] in Self.commands: #如果是可执行命令, try to find the executable function try:if hasattr (SE Lf,cmds[0]): # Find the logical function of the command in a class Func = Geta TTR (self, cmds[0]) #存在就获得该函数, and in the next pass in the parameter execution func (cm DS[1]) else:print ("Please enter the correct command format") continue Except Exception as E:print (e) def upload (self, dir): #这个函数用来上传 Pass def download (self, dir): #这个函数用来下载 Pass def directory (self, dir): #此函数查看文件目录 Passud = Uploaddownload ("localhost", Ud._command ()
Hasattr (), GetAttr (), SetAttr () in Python