Answers for "python classmethod"

12

class python

class MyClass(object):
  def __init__(self, x):
    self.x = x
Posted by: Guest on May-12-2020
2

python: @classmethod

class Float:
    def __init__(self, amount):
        self.amount = amount

    def __repr__(self):
        return f'<Float {self.amount:.3f}>'

    @classmethod
    def from_sum(cls, value_1, value_2):
        return cls(value_1 + value_2)


class Dollar(Float):
    def __init__(self, amount):
        super().__init__(amount)
        self.symbol = '€'

    def __repr__(self):
        return f'<Euro {self.symbol}{self.amount:.2f}>'


print(Dollar.from_sum(1.34653, 2.49573))
Posted by: Guest on August-10-2020
1

class methods in python

@classmethod
def func(cls, args...)
Posted by: Guest on November-14-2020
0

python classmethod

class point:
	def __init__(self, x, y):
    	self.x = x
        self.y = y
        
    @classmethod
    def zero(cls):
    	return cls(0, 0)
        
    def print(self):
    	print(f"x: {self.x}, y: {self.y}")
        
p1 = point(1, 2)
p2 = point().zero()
print(p1.print())
print(p2.print())
Posted by: Guest on December-07-2020
0

python classmethod

# classmethod example
In [20]: class MyClass:
    ...:     @classmethod
    ...:     def set_att(cls, value):
    ...:         cls.att = value
    ...:

In [21]: MyClass.set_att(1)

In [22]: MyClass.att
Out[22]: 1

In [23]: obj = MyClass()

In [24]: obj.att
Out[24]: 1

In [25]: obj.set_att(3)

In [26]: obj.att
Out[26]: 3

In [27]: MyClass.att
Out[27]: 3
Posted by: Guest on December-03-2020
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