Example 1: class methods in python
from datetime import date class Person: def __init__(self, name, age): self.name = name self.age = age @classmethod def fromBirthYear(cls, name, birthYear): return cls(name, date.today().year - birthYear) def display(self): print(self.name + "'s age is: " + str(self.age)) person = Person('Adam', 19) person.display() person1 = Person.fromBirthYear('John', 1985) person1.display()
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: class methods in python
@classmethod def func(cls, args...)
Example 5: 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())
Example 6: python classmethod
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
Comments
Post a Comment