class syntax in python code example
Example 1: declare class python
# To create a simple class:
class Shape:
def __init__():
print("A new shape has been created!")
pass
def get_area(self):
pass
# To create a class that uses inheritance and polymorphism
# from another class:
class Rectangle(Shape):
def __init__(self, height, width): # The constructor
super.__init__()
self.height = height
self.width = width
def get_area(self):
return self.height * self.width
Example 2: python define class
class uneclasse():
def __init__(self):
pass
def something(self):
pass
xx = uneclasse()
xx.something()
Example 3: classes in python
class Foo:
def __init__(self):
self.definition = Foo!
def hi():
# Some other code here :)
# Classes require an __init__ if you want to assign attributes. (self) defines what describes the attribs.
Example 4: how to declare a class in python
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
Example 5: class methods in python
from datetime import date
# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)
def display(self):
print(self.name + "'s age is: " + str(self.age))
person = Person('Adam', 19)
person.display()
person1 = Person.fromBirthYear('John', 1985)
person1.display()
Example 6: how to use class's in python
class person:
name = "jake"
age = 13
x = vars(person)
print(x)