1class Foo (object):
2 # ^class name #^ inherits from object
3
4 bar = "Bar" #Class attribute.
5
6 def __init__(self):
7 # #^ The first variable is the class instance in methods.
8 # # This is called "self" by convention, but could be any name you want.
9 #^ double underscore (dunder) methods are usually special. This one
10 # gets called immediately after a new instance is created.
11
12 self.variable = "Foo" #instance attribute.
13 print self.variable, self.bar #<---self.bar references class attribute
14 self.bar = " Bar is now Baz" #<---self.bar is now an instance attribute
15 print self.variable, self.bar
16
17 def method(self, arg1, arg2):
18 #This method has arguments. You would call it like this: instance.method(1, 2)
19 print "in method (args):", arg1, arg2
20 print "in method (attributes):", self.variable, self.bar
21
22
23a = Foo() # this calls __init__ (indirectly), output:
24 # Foo bar
25 # Foo Bar is now Baz
26print a.variable # Foo
27a.variable = "bar"
28a.method(1, 2) # output:
29 # in method (args): 1 2
30 # in method (attributes): bar Bar is now Baz
31Foo.method(a, 1, 2) #<--- Same as a.method(1, 2). This makes it a little more explicit what the argument "self" actually is.
32
33class Bar(object):
34 def __init__(self, arg):
35 self.arg = arg
36 self.Foo = Foo()
37
38b = Bar(a)
39b.arg.variable = "something"
40print a.variable # something
41print b.Foo.variable # Foo