oop - Is it common/good practice to test for type values in Python? -


is common in python keep testing type values when working in oop fashion?

class foo():     def __init__(self,barobject):         self.bar = setbarobject(barobject)      def setbarobject(barobject);         if (isinstance(barobject,bar):             self.bar = barobject         else:             # throw exception, log, etc.  class bar():     pass 

or can use more loose approach, like:

class foo():     def __init__(self,barobject):         self.bar = barobject  class bar():     pass 

nope, in fact it's overwhelmingly common not test type values, in second approach. idea client of code (i.e. other programmer uses class) should able pass kind of object has appropriate methods or properties. if doesn't happen instance of particular class, that's fine; code never needs know difference. called duck typing, because of adage "if quacks duck , flies duck, might duck" (well, that's not actual adage got gist of think)

one place you'll see lot in standard library, functions handle file input or output. instead of requiring actual file object, they'll take implements read() or readline() method (depending on function), or write() writing. in fact you'll see in documentation, e.g. tokenize.generate_tokens, happened looking @ earlier today:

the generate_tokens() generator requires 1 argument, readline, must callable object provides same interface readline() method of built-in file objects (see section file objects). each call function should return 1 line of input string.

this allows use stringio object (like in-memory file), or wackier dialog box, in place of real file.

in own code, access whatever properties of object need, , if it's wrong kind of object, 1 of properties need won't there , it'll throw exception.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -