1class Mammal:
2 def __init__(self, name):
3 self.name = name
4
5 def walk(self):
6 print(self.name + " is going for a walk")
7
8
9class Dog(Mammal):
10 def bark(self):
11 print("bark!")
12
13
14class Cat(Mammal):
15 def meow(self):
16 print("meow!")
17
18
19dog1 = Dog("Spot")
20dog1.walk()
21dog1.bark()
22cat1 = Cat("Juniper")
23cat1.walk()
24cat1.meow()
1class Person:
2 def __init__(self, _name, _age):
3 self.name = _name
4 self.age = _age
5
6 def sayHi(self):
7 print('Hello, my name is ' + self.name + ' and I am ' + self.age + ' years old!')
8
9p1 = Person('Bob', 25)
10p1.sayHi() # Prints: Hello, my name is Bob and I am 25 years old!
1class ClassName(object): #"(object)" isn't mandatory unless this class inherit from another
2 def __init__(self, var1=0, var2):
3
4 #the name of the construct must be "__init__" or it won't work
5 #the arguments "self" is mandatory but you can add more if you want
6 self.age = var1
7 self.name = var2
8
9 #the construct will be execute when you declare an instance of this class
10
11 def otherFunction(self):
12
13 #the other one work like any basic fonction but in every methods,
14 #the first argument (here "self") return to the class in which you are
15
1class ClassName:
2 self.attribute_1 = variable_1 #Set attributes for all object instances
3 self.attrubute_2 = variable_2
4
5 def __init__(self, attribute_3, attribute_4): #Set attributes at object creation
6 self.attribute_3 = attribute_3
7 self.attribute_4 = attribute_4
8
9 def method(self): #All methods should include self
10 print("This is a method example.") #Define methods just like functions
11
12
13object = Object(4, "string") #Set attribute_3 and attribute_4
14object.method() #Methods are called like this.
1def dump(obj):
2 for attr in dir(obj):
3 print("obj.%s = %r" % (attr, getattr(obj, attr)))
4