Skip to content

Instantly share code, notes, and snippets.

# both classes below implement Python properties using data descriptors
class StudentWithInlineProps:
def __init__(self, name="Default Name"):
self._name = name
# getting the values
def get_name(self):
print('Getting value')
return self._name
ychennay /
Created Mar 21, 2020
ForeignKeyDeferredAttribute example
class ForeignKeyDeferredAttribute(DeferredAttribute):
def __set__(self, instance, value):
if instance.__dict__.get(self.field.attname) != value and self.field.is_cached(instance):
instance.__dict__[self.field.attname] = value
class NonNullStringDescriptor:
def __init__(self, value: str = "Default Name"):
self.value = value
def __get__(self, instance, owner):
print(f"__get__({self}, {instance}, {owner})")
return self.value
def __set__(self, instance, value):
ychennay / data_descriptor_c.c
Last active Mar 20, 2020
data descriptor logic in C
View data_descriptor_c.c
f = NULL;
if (descr != NULL) {
Py_INCREF(descr); // increase the reference count of the descriptor
f = descr->ob_type->tp_descr_get; // access the descriptor's getter method from the descriptor's PyTypeObject ob_type
if (f != NULL && PyDescr_IsData(descr)) {
res = f(descr, obj, (PyObject *)obj->ob_type); // actual call to the descriptor's __get__
if (res == NULL && suppress &&
PyErr_ExceptionMatches(PyExc_AttributeError)) {
ychennay /
Last active Mar 19, 2020
name mangling
class Person:
def __init__(self, name):
self.__secret_attribute = 42 = name
if __name__ == "__main__":
person = Person("Yu")
# print(person.__secret_attribute) # AttributeError: 'Person' object has no attribute '__secret_attribute'
ychennay /
Last active Mar 19, 2020
Example of Person class in Java
package com.yuchen;
public class Student {
public String name;
public float gpa;
public String getName() {
return name;
# Add fields from abstract base class if it wasn't overridden.
for field in parent_fields:
if ( not in field_names and not in new_class.__dict__ and not in inherited_attributes):
new_field = copy.deepcopy(field)
new_class.add_to_class(, new_field)
# Replace parent links defined on this base by the new
# field. It will be appropriately resolved if required.
if field.one_to_one:
# Basic setup for proxy models.
if is_proxy:
base = None
for parent in [kls for kls in parents if hasattr(kls, '_meta')]:
if parent._meta.abstract:
if parent._meta.fields:
raise TypeError(
"Abstract base class containing model fields not "
"permitted for proxy model '%s'." % name
class Student(models.Model):
class SpecificStudent(Student):
class Meta:
proxy = True
def perform_student_specific_action(self):
# ...
# Inherit private fields (like GenericForeignKey) from the parent
# class
for field in base._meta.private_fields:
if in field_names:
if not base._meta.abstract:
raise FieldError(
'Local field %r in class %r clashes with field of '
'the same name from base class %r.' % (,