Which function is implicitly called in Python when setting a class variable via a class name? -


let's i've got class 'private' class variable , instance of class. want prevent setting variable outside of class or execute specific function when class variable being changed.

class someclass (object):     __classvar = 5     def getclassvar():         return someclass.__classvar  instance = someclass() 

the __classvar variable not directly readable outside of class (e.g. can't = someclass.__classvar or b = instance.__classvar) fact variable private doesn't stop me doing this:

someclass.__classvar = 6  instance.__classvar = 10 

even though doesn't assign value variable. e.g. code below still output 5.

class someclass (object):         __classvar = 5         def getclassvar():             return someclass.__classvar  instance = someclass() someclass.__classvar = 6 instance.__classvar = 10 print (getclassvar())  #outputs 5 

i know statement

instance.__classvar = 10 

is implicitly calling __setattr__ function, therefore can overload in class definition.

class someclass (object):     __classvar = 5     def getclassvar():             return someclass.__classvar      def __setattr__(cls, name, value):         print ("setting class variable via instance name")         #do specific 

however, don't know how control happens when attribute set via class name.

someclass.__var = 6   ##want specific when happens  

i suggest follow nick johnson's advice, howevre if in situation extremely need functionality, might interested in looking @ python metaclasses.

what can create own custom class inheriting type class, , overload __setattr__ there:

class yourmeta(type):     def __setattr__(self, name, value):         # stuff here 

and make metaclass of other class liek this:

class someclass(object):     __metaclass__ = yourmeta      # , on 

so now, have overloaded __setattr__ on class level.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

python - build a suggestions list using fuzzywuzzy -