Learning Python: Classes

define class

class MyClass:
    x = 5

create object (instance of a class)

p1 = MyClass()
print(p1.x)

init() function - the constructor

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Now lets create a object
p1 = Person("Jason", 4)

print(p1.name)
print(p1.age)

Objects also have methods

class PersonM:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def says_hello(self):
        return f"{self.name} says hello"

p2 = PersonM("Snow", 30)
print(p2.says_hello())

**self parameter allows the object to access variables that belongs to the class **

del p1 # delete the object
del p2

print(p1) # will throw an error

Inheritance

class Person:
    def __init__(self, fname, lname):
        self.first_name = fname
        self.last_name = lname
    
    def print_name(self):
        print(f"{self.first_name} {self.last_name}")
class Student(Person):
    pass


rahul = Student("SR", "K")
rahul.print_name()
class StudentM(Person):
    def __init__(self, fname, lname):
        if lname is None:
            lname = "GET A NAME"
        super().__init__(fname, lname)

    def print_name(self):
        return f"{self.first_name} {self.last_name}"

    def conduct(self):
        print(f"{self.print_name()} is Flamboyant")

mungeri_lal = StudentM("Lal", None)
mungeri_lal.conduct()

Iter

fruits = ("apple", "banana", "cherry")
myit = iter(fruits)
print(next(myit))
print(next(myit))
print(next(myit))

creating your iterator

implement iter() and next()

class MyNumbers:
    def __iter__(self):
        self.a = 1
        return self

    def __next__(self):
        x = self.a
        self.a += 1
        if x > 4:
            raise StopIteration
        return x


mynums = MyNumbers()
myiter = iter(mynums)
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))
print(next(myiter))