tgoop.com/djangolearn_ir/1178
Create:
Last Update:
Last Update:
کلاس های تو در تو در پایتون یا inner class یا nested class
توی پایتون میشه یه کلاس رو توی کلاس دیگه تعریف کرد، اینجوری مثلا:
class Car:
def __init__(self, name, engine_type):
self.name = name
self.engine = self.Engine(engine_type)
class Engine:
def __init__(self, engine_type):
self.type = engine_type
def start(self):
print(f"{self.type} engine is starting...")
اینجوری استفاده کنیم:
my_car = Car("405", "tu5")
print(my_car.name) #405
my_car.engine.start() # tu5 engine is staringاین حرکت زیاد مرسوم نیست، ولی مثلا برای این کدهای بالا، کلاس Engine تا Car وجود نداشته باشه، قابل استفاده نیست. و یه جورایی صراحتا مشخص کردیم که کلاس Engine وابسته اس به Car.
استفاده ش توی جنگو رو که می دونید کجاهاس؟
توی مدل ها، توی فرم ها و... وقتی یه سری تنظیمات رو توی Meta تعریف می کنیم.
البته، توی جنگو مثل کدی که بالا نوشتم استفاده نشده، این تیکه کد از سورس جنگوعه و داره از Meta استفاده میکنه:
class ModelBase(type):
"""Metaclass for all models."""
def __new__(cls, name, bases, attrs, **kwargs):
super_new = super().__new__
# Also ensure initialization is only performed for subclasses of Model
# (excluding Model class itself).
parents = [b for b in bases if isinstance(b, ModelBase)]
if not parents:
return super_new(cls, name, bases, attrs)
# Create the class.
module = attrs.pop("__module__")
new_attrs = {"__module__": module}
classcell = attrs.pop("__classcell__", None)
if classcell is not None:
new_attrs["__classcell__"] = classcell
attr_meta = attrs.pop("Meta", None)
# Pass all attrs without a (Django-specific) contribute_to_class()
# method to type.__new__() so that they're properly initialized
# (i.e. __set_name__()).
اون attr_meta داره تنظیمات رو بر میداره و...
BY جنگولرن
Share with your friend now:
tgoop.com/djangolearn_ir/1178
