Skip to content

Instantly share code, notes, and snippets.

@cosven
Created August 16, 2017 02:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cosven/0abb9a5bc52f3cc5109602e870ce709f to your computer and use it in GitHub Desktop.
Save cosven/0abb9a5bc52f3cc5109602e870ce709f to your computer and use it in GitHub Desktop.
tranditional model definition ways in python
"""
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