use of class method in python code example
Example 1: python define class
class uneclasse():
def __init__(self):
pass
def something(self):
pass
xx = uneclasse()
xx.something()
Example 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))
Example 3: class methods parameters python
class Foo (object):
bar = "Bar"
def __init__(self):
self.variable = "Foo"
print self.variable, self.bar
self.bar = " Bar is now Baz"
print self.variable, self.bar
def method(self, arg1, arg2):
print "in method (args):", arg1, arg2
print "in method (attributes):", self.variable, self.bar
a = Foo()
print a.variable
a.variable = "bar"
a.method(1, 2)
Foo.method(a, 1, 2)
class Bar(object):
def __init__(self, arg):
self.arg = arg
self.Foo = Foo()
b = Bar(a)
b.arg.variable = "something"
print a.variable
print b.Foo.variable
Example 4: how to use class's in python
class person:
name = "jake"
age = 13
x = vars(person)
print(x)