Object-Oriented Programming in Python
Class Definition
class MyClass:
foo = 11
def bar(self):
return 'hello object'
MyClass.foo
and MyClass.bar
are valid attribute references, returning an integer and a function object, respectively
Class instantiation
class MyClass:
foo = 11
def bar(self):
return 'hello object'
instant = MyClass()
instant.bar() # call bar function
However, Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named __init__()
, like this:
class MyClass:
foo = 11
def __init__(self, a, b):
self.foo1 = a
self.foo2 = b
def bar(self):
return 'hello object'
instant = MyClass(2,4)
print(instant.foo1, instant.foo2) #2 4
Class and Instance Variables
Class variable shared by all instances
class MyClass:
addMe = 1
def __init__(self, a, b):
self.foo1 = a
self.foo2 = b
def bar(self):
return 'hello object'
def add(self,x):
self.addMe += x
a = MyClass(2,4)
b = MyClass(3,6)
print(a.addMe)
a.add(2)
print(a.addMe)
b.add(3)
print(a.addMe)
print(b.addMe)
#1
#3
#3
#4
But sometimes it may lead to mistakes.(why)
class MyClass:
addMe = []
def __init__(self, a, b):
self.foo1 = a
self.foo2 = b
def bar(self):
return 'hello object'
def add(self,x):
self.addMe.append(x)
a = MyClass(2,4)
b = MyClass(3,6)
print(a.addMe)
a.add(2)
print(a.addMe)
b.add(3)
print(a.addMe)
#[]
#[2]
#[2, 3]
Reference
[9. Classes](