python reference class function code example

Example 1: class methods parameters python

class Foo          (object):
    # ^class name  #^ inherits from object

    bar = "Bar" #Class attribute.

    def __init__(self):
        #        #^ The first variable is the class instance in methods.  
        #        #  This is called "self" by convention, but could be any name you want.
        #^ double underscore (dunder) methods are usually special.  This one 
        #  gets called immediately after a new instance is created.

        self.variable = "Foo" #instance attribute.
        print self.variable, self.bar  #<---self.bar references class attribute
        self.bar = " Bar is now Baz"   #<---self.bar is now an instance attribute
        print self.variable, self.bar  

    def method(self, arg1, arg2):
        #This method has arguments.  You would call it like this:  instance.method(1, 2)
        print "in method (args):", arg1, arg2
        print "in method (attributes):", self.variable, self.bar


a = Foo() # this calls __init__ (indirectly), output:
                 # Foo bar
                 # Foo  Bar is now Baz
print a.variable # Foo
a.variable = "bar"
a.method(1, 2) # output:
               # in method (args): 1 2
               # in method (attributes): bar  Bar is now Baz
Foo.method(a, 1, 2) #<--- Same as a.method(1, 2).  This makes it a little more explicit what the argument "self" actually is.

class Bar(object):
    def __init__(self, arg):
        self.arg = arg
        self.Foo = Foo()

b = Bar(a)
b.arg.variable = "something"
print a.variable # something
print b.Foo.variable # Foo

Example 2: class item assignment python

class ItemAssign():
# initialize
    def __init__(self, a, b):
        self.a = a
        self.b = b
# set item
    def __setitem__(self, k, v):
        if k == "a":
            self.a = v
        if k == "b":
            self.b = v
# get item
    def __getitem__(self, k):
        if k == "a":
            return self.a
        if k == "b":
            return self.b
# len
    def __len__(self):
        return 2
# del item
    def __delitem__(self, k):
        self[k] = None
# instance = ItemAssign(2, 4)
# for x in instance:
    def __iter__(self):
        yield self.a
        yield self.b