- Class
- Steps
1. Create class
2. Create three instance methods within the class
- Initiator method, asigned value argument to value object.
- increment method, change value object attribute
- decrement method, change value object attribute
3. Create instance
4. Call instance methods
POINT : Must create instance first, call it then.
1.
class Counter():
2.
def __init__(self, value=0):
self.value=value
def increment(self, delta=1):
self.value+=delta
def decrement(self, delta=1):
self.value-=delta
3.
counter=Counter()
4.
counter.value
>>>0
counter.increment(3)
>>>3
counter.decrement(2)
>>>
1
- classmethod
- Steps
1. Define class
2. Define one instance method and two classmethods
- One instance method : Initiator method, asigned email, password argument to email, password object.
- Two classmethods : Declare classmethod fromTuple using with decorator@, first argument is class itself(cls).
- Two classmethods : Declare classmethod fromDictionary using with decorator@, first argument is class itself(cls).
3. Create object
4. Call class.classmethod
POINT : It does not create instance. When call classmethods, class itself be called as an first argument. It creates User initiator, asign to classmethod.
1.
class User:
2.
def __init__(self, email, password):
self.email=email
self.password=password
@classmethod #
def fromTuple(cls, tup):
return cls(tup[0], tup[1])
@classmethod
def fromDictionary(cls, dic):
return cls(dic['email'], dic['password'])
3.
user=User('google@google.com','1234')
print(user.email, user.password)
4.
user=User.fromTuple(('google@google.com','1234'))
print(user.email, user.password)
- staticmethod
- Steps
1. Define class
2. Define two static methods
- Define toCamelcase methods as static using decorator @staticmethod
- Define toSnakecase methods as static using decorator @staticmethod
3. Call class.staticmethod
POINT : It does not create instance. There is no argument in the staticmethod.
1.
class StringUtils:
2.
@staticmethod
def toCamelcase(text):
words=iter(text.split("_"))
return next(words)+"".join(i.title() for i in words)
@staticmethod
def toSnakecase(text):
letters=["_"+i.lower() if i.isupper() else i for i in text]
return "".join(letters).lstrip("_")
3.
print(StringUtils.toCamelcase('last_modified_date'))
print(StringUtils.toSnakecase('last_modified_date'))
'Basic Python' 카테고리의 다른 글
__new__, __init__ (0) | 2022.07.13 |
---|---|
Underscore(_) (0) | 2022.07.05 |
TypeError : Can't instantiate abstract class with abstract method (0) | 2022.06.29 |
title, items (0) | 2022.06.29 |
tqdm (0) | 2022.04.07 |