# define a new class
class MyClass:
= 123
x
def greet(self):
return "Hello from MyClass"
= MyClass()
x
# see class attributes
x.greet() x.x
123
Python classes basics
The stuff below is like Python classes 101. It’s mostly either directly copied from or else loosely inspired by the Python manual
# define a new class
class MyClass:
= 123
x
def greet(self):
return "Hello from MyClass"
= MyClass()
x
# see class attributes
x.greet() x.x
123
# we can define an __init()__ method to help us create object instances with specific initial states
class MyClass:
def __init__(self, x):
self.x = x
def greet(self):
return "Hello from MyClass"
= MyClass(x=1)
y y.x
1
# class variables will be shared by all instances, whereas instance variables will be unique to each instance
class Dog:
= "canine" # class variable
kind
def __init__(self, name):
self.name = name
= Dog("Nala")
d = Dog("Adi")
e
d.name
d.kind
e.name
# below might be a way to create a Dog class where each dog has its own set of tricks
class Dog:
= "canine"
kind
def __init__(self, name):
self.name = name
self.tricks = []
def add_trick(self, trick):
self.tricks.append(trick)
= Dog("Nala")
d "roll over")
d.add_trick("sit")
d.add_trick(
d.tricks
['roll over', 'sit']
Class inheritance lets classes inherit variables and methods from other classes
# classes also support inheritance
class Animal:
def __init__(self, name):
self.name = name
class Cat(Animal):
= "cat"
kind
= Cat("Fluffy")
a
a.name a.kind
'cat'