Sunday, February 18, 2024

python doodles

"""
#alternative ways to create an instance of a class
class A():
    def __init__(self, num=None, name=None):
        self._num = num
        self._name = name
    
    @classmethod
    def createByNumber(cls, num=None):
        return cls(num=num)
    
    @classmethod
    def createByName(cls, name=None):
        return cls(name=name)
        
    def printMe(self):
        print("num {}".format(self._num))
        print("name {}".format(self._name))
        
a = A.createByNumber(21)
a.printMe()

a1 = A.createByName("yaaay!")
a1.printMe()

#num 21
#name None
#num None
#name yaaay!
"""

"""
#simple class composition - one class has a variable which is another class
class Zoo(object):
    def __init__(self):
        self._animals = []
        self._animals = [Lion(), Dog()]
    def hello(self):
        for animal in self._animals:
            #skip animals that are not Lions or Dogs
            if not isinstance(animal, Lion) and not isinstance(animal, Dog):
                continue
            animal.greeting()
        
class Lion(object):
    def greeting(self):
        print("roaarrr")

class Dog(object):
    def greeting(self):
        print("rufff")
        
z = Zoo()
z.hello()
#roaarrr
#rufff
"""


"""
#doodle creating an instance of a class using a dictionary
class Letter(object):
    def __init__(self, **kwargs):
        for k,v in kwargs.items():
            setattr(self, k, v)
            
    def printParams(self):
        for k in self.__dict__.keys():
            print("var {}".format(k), getattr(self, k))
        
dat = dict( a=1,
            b=2,
            c=3,
            d=4,
            e=5 )
obj = Letter(**dat)
obj.printParams()
#('var a', 1)
#('var c', 3)
#('var b', 2)
#('var e', 5)
#('var d', 4)

#inspired by
#https://stackoverflow.com/questions/4075190/what-is-how-to-use-getattr-in-python
#https://stackoverflow.com/questions/1398022/looping-over-all-member-variables-of-a-class-in-python
""" 
Happy Sketching!