[Tutor] OOPs and general Python questions.
Cameron Simpson
cs at cskk.id.au
Wed Apr 19 05:36:58 EDT 2023
On 19Apr2023 18:30, mhysnm1964 at gmail.com <mhysnm1964 at gmail.com> wrote:
>What is a super class?
It is a parent class of some class.
Suppose I've got a class like this:
class int16(int):
''' A subclass of int which prints in base 16.
'''
def __str__(self):
return f'0x{self:x}'
This behaves just like an int except that converting it to a string
results in a base 16 representation:
>>> class int16(int):
... def __str__(self):
... return f'0x{self:x}'
...
>>> i=int16(15)
>>> i
15
>>> str(i)
'0xf'
>>> print(i)
0xf
Here the superclass of int16 is int.
>Does python care the order of classes and methods?
Order of definition? As a dynamic language, things are defined by
executing them. So they happen in the order they're in the file. That
means that if defining B requires use of A, then A needs to have been
defined by the time you go to define B.
class A:
def method(self, x):
print("A:", x)
class B(A):
def method(self, x):
print("B:", x)
Here, the class A needs to be defined in order to define the class B,
because B subclasses A. Swapping them around won't work. try it!
It is no different to this:
x = 1
y = x * 2
You can't swap these around either, for exactly the same reason.
Cheers,
Cameron Simpson <cs at cskk.id.au>
More information about the Tutor
mailing list