Let's look into this Python 2 shell.
>>> class X1:
... a = 1
...
... X2 = type('X2', (), {'a': 1})
>>> type(X1)
0: <type 'classobj'>
>>> type(X2)
1: <type 'type'>
>>> import types
>>> assert types.ClassType is type(X1)
Basically type
in the new-style classes' default metaclass. If you want metaprogramming in the old style, you can use types.ClassType
in the same way.
>>> X3 = types.ClassType('X3', (), {
'a': 1
}) >>>
X3.__bases__
2: ()
Object Is Subclassed During Dynamic Type Creation But Not During Classic Class Definition In Python2, › Object is subclassed during dynamic type creation but not during classic class definition in python2 , Classes can be dynamically created using the type () function in Python. The type () function is used to return the type of the object. The above syntax returns the type of object. , 1 week ago is it possible to access the current object during creation in javascript? Example: var data = {x: 1, z:x} OR. ... Access to class object during class definition. ... object is subclassed during dynamic type creation but not during classic class definition in python2.
class X: a = 1
class X: a = 1
class X:
a = 1
>>>X.__bases__ # Python 2 () >>>X.__bases__ # Python 3 (<class 'object'>,)
>>>
X.__bases__ # Python 2 () >>>
X.__bases__ # Python 3 (<class 'object'>,)
X = type("X", (object, ), {
"a": 1
}) name ^ ^ bases ^ "class"
body
X = type("X", ( ), {"a":1}) ^ empty bases tuple
>>>X.__bases__ # Python 2 (<type 'object'>,) >>>X.__bases__ # Python 3 (<class 'object'>,)
>>>class X1: ...a = 1 ... ... X2 = type('X2', (), {'a': 1}) >>>type(X1) 0: <type 'classobj'>>>>type(X2) 1: <type 'type'>>>>import types >>>assert types.ClassType is type(X1)
>>> X3 = types.ClassType('X3', (), {
'a': 1
}) >>> X3.__bases__ 2: ()
By Bernd Klein. Last modified: 01 Feb 2022.
x = [4, 5, 9]
y = "Hello"
print(type(x), type(y))
<class 'list'>
<class 'str'>
print(type(list), type(str))
<class 'type'>
<class 'type'>
x = [4, 5, 9]
y = "Hello"
print(type(x), type(y))
print(type(type(x)), type(type(y)))
<class 'list'>
<class 'str'>
<class 'type'>
<class 'type'>
For instances of built-in types (and for new-style classes in general), x.__class__ is now the same as type(x): ,When using multiple inheritance, you can mix classic classes and built-in types (or types derived from built-in types) in the list of base classes. (This is new in Python 2.2b2; in earlier versions you couldn't.) ,The specs of the built-in types that are subclassable ,You cannot use slots with "variable-length" built-in types as base class. Variable-length built-in types are long, str and tuple.
class A:
def foo(self): pass
class B(A): pass
class C(A):
def foo(self):
B.foo(self)
The trap has now been laid, and will be sprung the moment the application needs to filter messages but write them to a socket instead of a file. None of the existing classes covers that case. If the developer plows on ahead with subclassing and creates a FilteredSocketLogger that combines the features of both classes, then the subclass explosion is underway.,And so the subclass explosion is avoided! Logger objects and adapter objects can be freely mixed and matched at runtime without the need to create any further classes:,But whether you give each derived class its own __init__() or design them to chain together, your unit tests of the original FilteredLogger and SocketLogger can’t by themselves guarantee that the classes initialize correctly when combined.,The tuple of classes passed to type() has the same meaning as the series of base classes in a class statement. The type() call above creates a new class through multiple inheritance from both a filtered logger and an output logger.
import sys
import syslog
# The initial class.
class Logger(object):
def __init__(self, file):
self.file = file
def log(self, message):
self.file.write(message + '\n')
self.file.flush()
# Two more classes, that send messages elsewhere.
class SocketLogger(Logger):
def __init__(self, sock):
self.sock = sock
def log(self, message):
self.sock.sendall((message + '\n').encode('ascii'))
class SyslogLogger(Logger):
def __init__(self, priority):
self.priority = priority
def log(self, message):
syslog.syslog(self.priority, message)
# New design direction: filtering messages.
class FilteredLogger(Logger):
def __init__(self, pattern, file):
self.pattern = pattern
super().__init__(file)
def log(self, message):
if self.pattern in message:
super().log(message)
# It works.
f = FilteredLogger('Error', sys.stdout)
f.log('Ignored: this is not important')
f.log('Error: but you want to see this')
Error: but you want to see this
Logger FilteredLogger SocketLogger FilteredSocketLogger SyslogLogger FilteredSyslogLogger
import socket
class FileLikeSocket:
def __init__(self, sock):
self.sock = sock
def write(self, message_and_newline):
self.sock.sendall(message_and_newline.encode('ascii'))
def flush(self):
pass
class FileLikeSyslog:
def __init__(self, priority):
self.priority = priority
def write(self, message_and_newline):
message = message_and_newline.rstrip('\n')
syslog.syslog(self.priority, message)
def flush(self):
pass
sock1, sock2 = socket.socketpair()
fs = FileLikeSocket(sock1)
logger = FilteredLogger('Error', fs)
logger.log('Warning: message number one')
logger.log('Error: message number two')
print('The socket received: %r' % sock2.recv(512))
Last modified: Feb 4, 2022, by MDN contributors
class Person {
name;
constructor(name) {
this.name = name;
}
introduceSelf() {
console.log(`Hi! I'm ${this.name}`);
}
}
const giles = new Person('Giles');
giles.introduceSelf(); // Hi! I'm Giles
class Animal {
sleep() {
console.log('zzzzzzz');
}
}
const spot = new Animal();
spot.sleep(); // 'zzzzzzz'
class Professor extends Person {
teaches;
constructor(name, teaches) {
super(name);
this.teaches = teaches;
}
introduceSelf() {
console.log(`My name is ${this.name}, and I will be your ${this.teaches} professor.`);
}
grade(paper) {
const grade = Math.floor(Math.random() * (5 - 1) + 1);
console.log(grade);
}
}
const walsh = new Professor('Walsh', 'Psychology');
walsh.introduceSelf(); // 'My name is Walsh, and I will be your Psychology professor'
walsh.grade('my paper'); // some random grade
class Student extends Person {
#year;
constructor(name, year) {
super(name);
this.#year = year;
}
introduceSelf() {
console.log(`Hi! I'm ${this.name}, and I'm in year ${this.#year}.`);
}
canStudyArchery() {
return this.#year > 1;
}
}
In one respect, however, we can’t get away from thinking about subclassing when we write classes in Java. Every Java class is automatically a subclass of Object, and automatically inherits methods like toString(), equals(), and hashCode(). We often need to override these inherited implementations, replacing them with our own implementations, in order for our class to behave correctly.,Implementing an interface is one way to make a subtype of another type. Another technique, which you may have seen before, is subclassing. Subclassing means defining a class as an extension, or subclass, of another class, so that:,In the design of the Java collection classes, in order to use the built-in Java Set interface, clients must also know about a specific implementation class like HashSet in order to make a new mutable Set instance:,We also discuss subtyping as a relationship between two types determined by their specs, and distinguish it from subclassing, which involves reps as well.
Consider this Java interface and Java class, which are intended to represent a curve in the 2D plane:
/** Represents an immutable curve in the plane. */
public interface Curve {
/** make a one-point curve */
/* A */
public Curve(double x, double y);
/** @return true if the point (x,y) lies on this curve */
public boolean contains(double x, y);
/** @return a curve formed by connecting this with that */
/* B */
public ArrayCurve join(Curve that);
}
/** Implementation of Curve. */
public class ArrayCurve implements Curve {
/** make a one-point curve */
public ArrayCurve(double x, double y) {
...
}
/** @return a curve formed by connecting this with that */
public ArrayCurve join(Curve that) {
...
}
/** extend this curve with a segment to the point (x,y) */
public void add(double x, double y) {
...
}
}
class ArrayList<E> implements List<E> {
...
}
interface SortedSet<E> extends Set<E> {
...
}
/** ... spec says nothing at all about mutation or mutability ... */
List<String> toUpperCase(List<String> names)
If the answer for some line is “static error” or “dynamic error”, then assume that line is simply commented out so that the rest of the code can still compile and run.
/*1*/ List<String> list = new ArrayList<String>();
/*2*/
list = Collections.unmodifiableList(list);
/*1*/ List<String> list = new ArrayList<String>();
/*2*/ list = Collections.unmodifiableList(list);
/*3*/ list = List.of("glorp");
/*4*/ list.add("fleeb");
/*5*/ list = new List<String>();
/*6*/ Set<String> set = list; //list has no repeats!
/*7*/ Collection<String> collection = list;
If the answer for some line is “static error” or “dynamic error”, then assume that line is simply commented out so that the rest of the code can still compile and run.
/*1*/ List<String> list = new ArrayList<String>();
/*2*/
list = Collections.unmodifiableList(list);
/*4*/
list.add("fleeb");
/*5*/ list = new List<String>();
/** An immutable rectangle. */
public interface ImmutableRectangle {
/** @return the width of this rectangle */
public int getWidth();
/** @return the height of this rectangle */
public int getHeight();
}
/** An immutable square. */
public class ImmutableSquare implements ImmutableRectangle {
private final int side;
/** Make a new side x side square. */
public ImmutableSquare(int side) {
this.side = side;
}
/** @return the width of this square */
public int getWidth() {
return side;
}
/** @return the height of this square */
public int getHeight() {
return side;
}
}
/** A mutable rectangle. */
public interface MutableRectangle {
// ... same methods as ImmutableRectangle above ...
/** Set this rectangle's dimensions to width x height. */
public void setSize(int width, int height);
}
/** A mutable square. */
public class MutableSquare implements MutableRectangle /* hopefully? */ {
private int side;
// ... same constructor and methods as ImmutableSquare above ...
// TODO implement setSize(..)
}
For each possible MutableSquare.setSize(..)
spec below, is it a valid strengthening of MutableRectangle.setSize()
?
/**
* Set this square's dimensions to width x height.
* Requires width = height.
*/
public void setSize(int width, int height) {
...
}
/**
* If width = height, set this square's dimensions to width x height.
* Otherwise, new dimensions are unspecified.
*/
public void setSize(int width, int height) {
...
}
/**
* Set this square's dimensions to side x side.
*/
public void setSize(int side) {
...
}