Created
August 16, 2017 02:17
-
-
Save cosven/0abb9a5bc52f3cc5109602e870ce709f to your computer and use it in GitHub Desktop.
tranditional model definition ways in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
there are three typical ways to define a model in python. | |
""" | |
# --------------------------------------------------- | |
# use namedtuple: simple but not flexible or powerful | |
# --------------------------------------------------- | |
from collections import namedtuple | |
User = namedtuple('User', ['name', 'age', 'email', 'telephone', 'fans']) | |
user = User( | |
name='Tom', | |
age=10, | |
email='tom@github.com', | |
telephone='111-111222', | |
fans=[] | |
) | |
print(user.name) | |
# user.name = 'Hey' # AttributeError | |
# ------------------------------------------- | |
# create a class: redundant,hard to maintain | |
# ------------------------------------------- | |
class User(object): | |
def __init__(self, name, age, email, telephone, fans=[]): | |
self.name = name | |
self.age = age | |
self.email = email | |
self.telephone = telephone | |
self.fans = fans | |
class User(object): | |
def __init__(self, data): | |
self._data = data | |
@property | |
def name(self): | |
return self._data.get('name', '') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment