Answers for "python function in class"

22

how to make a class in python

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!
Posted by: Guest on November-17-2019
0

python class with function @classmethod

import numpy as np 

class Unknown:
    def __init__(self, p1, p2, p3, p4):
        self.p1 = p1
        self.p2 = p2
        self.p3 = p3
        self.p4 = p4

    def random_func(self, p5):
        '''Function that return an array from a range,
        with specified shape, and name'''
        step1 = np.array(np.arange(self.p1)).reshape((self.p2,self.p3))
        step2 = self.p4
        print(step2)
        print('Printing p5 =>', p5)
        return step1

    @classmethod
    def a_class_method(self, p6):
        print(f'This is a class method: {p6}')
        
        

#PREPARE PARAMS 
# cust_arr = random_func(self.p1, self.p2, self.p3, self.p4)
params = {'p1':12, 'p2':3, 'p3':4, 'p4':'Creating customized array with params'}

#INSTANCIATE
here = Unknown(**params)#16, 4, 4, 'This actually work too!')
here.random_func('This is P5')
Unknown.a_class_method('P6 value is now used !')
Posted by: Guest on August-29-2021

Python Answers by Framework

Browse Popular Code Answers by Language