python - How to specify a variable as a member variables of a class or of an instance of the class? -
in latest python 2.7.x:
given member variable inside definition of class, member variable @ class level in sense single variable shared instances of class?
in definition of class, how can specify
- which member variables in definition of class belong class , shared instances of class, ,
- which belong particular instance of class , not instance of class?
how can refer member variable of class?
how can refer member variable of instance of class?
do answers above questions appear somewhere in official python language reference https://docs.python.org/2/reference/? can't find them there.
thanks.
you might want use terminology "class variable" , "instance variable" here, that's usual language in python.
class foo(object): var1 = "i'm class variable" def __init__(self, var2): self.var2 = var2 # var2 instance variable
the scoping rule need know in python lookup order names - "legb", local, enclosing, global , builtin.
the class scoped variable var1
still has looked "get attribute", can access foo.var1
or self.var1
. of course, can access elsewhere inside class definition block, example usage "local" scope.
when see self.var1
, can't know whether instance or class variable (nor, in fact, if name bound object @ all!). know attribute tried on object before it's tried on class.
indeed, instance variable can shadow class variable of same name:
>>> f1 = foo(var2='f1_2') >>> f2 = foo(var2='f2_2') >>> f2.var1 "i'm class variable" >>> f2.var1 = "boom!" # shadows class variable >>> f1.var1, foo.var1, f2.var1 # but: class variable still exists ("i'm class variable", "i'm class variable", 'boom!') >>> del f2.var1 # restores name resolution on foo object >>> f2.var1 "i'm class variable"
to complicate matters, can write fancy code makes class variables behave more instance variables; notable example "fields" of orm. example in django, may define integer field on model class - when lookup name on instance of model, actual integer returned (not integerfield
object).
if you're interested in advanced usage of attribute access, read on descriptor protocol. mundane classes can safely ignore details, it's worth knowing usual resolution of instance variables , class variables has lower precedence descriptors may have been defined on class.
Comments
Post a Comment