Python: What is the difference between G(F); a = 1; and G = F(1) -
class f(object): # word 'object' meaningful? def __init__(self,a,b,c): self.a = self.b = b self.c = c class g(f): # how subclass definition = 1 b = 2 c = 3 h = f(1,2,3) # differ one?
in python2,
class f(object)
declares f
new-style class (as opposed classic class). in python3, classes new-style, object
can omitted there.
certain python features, such properties , super, work new-style classes. new-style classes have attributes , methods, mro
, classic classes lack.
classic classes present backwards compatibility. classes define should new-style classes.
class g(f):
makes g
subclass of f
, whereas
h = f(1,2,3)
makes h
instance of f
.
note pep8 style guide recommends classes named capwords, while instances given lowercase names. (so h
should h
...)
be sure aware of difference between class attributes , instance attributes. definition
class f(object): def __init__(self,a,b,c): self.a = self.b = b self.c = c
gives instances of f
instance attributes. assignments self.a = a
, etc. executed when __init__
method called, happens when instance of f
created. example, when say
h = f(1,2,3)
notice these instance attributes can inspected in h.__dict__
:
>>> h.__dict__ >>> {'a': 1, 'b': 2, 'c': 3}
they not in f.__dict__
.
>>> f.__dict__ >>> dict_proxy({'__dict__': <attribute '__dict__' of 'f' objects>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'f' objects>, '__doc__': none, '__init__': <function __init__ @ 0xae90ae4>})
keys in f.__dict__
class attributes. shared all instances of f
. instance attributes specific each instance, , can differ between instances.
note since h
instance of f
, h
can access f
's class attributes own instance attributes. instance,
>>> h.__module__ >>> '__main__'
that's basics, though there lot more said python attribute lookup rules. see chaturvedi more complete description of these rules.
now when say
class g(f): = 1 b = 2 c = 3
you defining a
, b
, c
class attributes of g
. notice these class attributes can inspected in g.__dict__
:
>>> g.__dict__ >>> dict_proxy({'a': 1, '__module__': '__main__', 'b': 2, 'c': 3, '__doc__': none})
Comments
Post a Comment