object - Making a class act as string in Python when you have both str and unicode -
Disclaimer: I'm using Python 2.6 for very awkward reasons. This is what it is.
I am trying to act as a string in the form of an object such as:
class setting (str): def __new __ (cls, value , Source): Return super (setting, CLS) .__ new__ (CLS, value) def __init __ (self, value, source): self.value = value self.source = source < P> It works very well clearly;) But: I need to support both Unicode and Str object. So what I would like to do is expand the buststring unfortunately, for completely logical reasons; Just does not work by changing the beststring to Super Class and returns the error:
Typure: the bassstring type can not be institute Any idea how can I go about fixing this? Thank you. :)
OK, sorry, but this code is awful, it's hard to understand, any Underlying class subclassing (such as str, file) is generally a bad idea, especially in production code.
What I would recommend is a general approach, creating a square with two variables and overriding a particular operator to achieve the desired result (i.e. it works like a str:
class setting: def __init __ (self, value, source): self.value = value self.source = source def __add __ (auto, rhs): # object irreversible return setting (self.value + rhs , Self.source) However in the interest of the extreme Python code, for which I used a single case Can not always think of the best way to do it), here is an alternative solution:
class setting (object): def __new __ (CLS, value, source): # The correct base class base_class = str ifinstance (value, str) other Unicode #Construct with the correct base new settings class new_type = type (cls._ _name__, (base_class,), dict (cls .__ dict__) Return base_class .__ New __ (new_type, value) def __init __ (self, value, source): self.value = value self.source = source This idea is dynamically given the type of value Right on the basis Creating a class that edge. Yes, it should be even more scary and you should not use it. You can change it so that the value of the base class becomes 'value', but I thought it is a bit more readable.
The reason for this is that you can not use the beststring, it is an abstract class or at least it works like one so when you did:
< Code> Return Super (Setting, CLS) .___NEW__ (CLS, Value) A new example of the best string of this, tried to turn it on, It does not make any sense since then, nothing to call.
Comments
Post a Comment