xxxxxxxxxx
class car:
def __init__(self, model, color):
self.model = model
self.color = color
tesla = car("model 3", "black")
xxxxxxxxxx
class Person:
def __init__(self, _name, _age):
self.name = _name
self.age = _age
def sayHi(self):
print('Hello, my name is ' + self.name + ' and I am ' + self.age + ' years old!')
p1 = Person('Bob', 25)
p1.sayHi() # Prints: Hello, my name is Bob and I am 25 years old!
xxxxxxxxxx
class Mammal:
def __init__(self, name):
self.name = name
def walk(self):
print(self.name + " is going for a walk")
class Dog(Mammal):
def bark(self):
print("bark!")
class Cat(Mammal):
def meow(self):
print("meow!")
dog1 = Dog("Spot")
dog1.walk()
dog1.bark()
cat1 = Cat("Juniper")
cat1.walk()
cat1.meow()
xxxxxxxxxx
class ClassName(object): #"(object)" isn't mandatory unless this class inherit from another
def __init__(self, var1=0, var2):
#the name of the construct must be "__init__" or it won't work
#the arguments "self" is mandatory but you can add more if you want
self.age = var1
self.name = var2
#the construct will be execute when you declare an instance of this class
def otherFunction(self):
#the other one work like any basic fonction but in every methods,
#the first argument (here "self") return to the class in which you are
xxxxxxxxxx
class Greet:
def __init__(self, names):
self.names = names
def say_hello(self):
for name in self.names:
print("Hello " + name)
xxxxxxxxxx
#Source: https://vegibit.com/python-class-examples/
class Vehicle:
def __init__(self, brand, model, type):
self.brand = brand
self.model = model
self.type = type
self.gas_tank_size = 14
self.fuel_level = 0
def fuel_up(self):
self.fuel_level = self.gas_tank_size
print('Gas tank is now full.')
def drive(self):
print(f'The {self.model} is now driving.')
obj = Vehicle("Toyota", "Carola", "Car")
obj.drive()
xxxxxxxxxx
class class_name:
def __init__(self):
# class variables(can be used all over the class)
pass
first_class = class_name() # creating the class
xxxxxxxxxx
class Person:
def say_hi(self):
print('Hello, how are you?')
p = Person()
p.say_hi()
# The previous 2 lines can also be written as
# Person().say_hi()
xxxxxxxxxx
class MyClass:
def __init__(self, x, y):
self.x = x
self.y = y
def my_method(self):
return self.x * self.y