Difference between __init__ (again) and nothing ...

S

Stef Mientki

What's the difference between using __init__ and using nothing,
as the examples below.

<Python-1>
class cpu:
PC = 4


<Python-2>
class cpu:
def __init__:
self.PC = 4

thanks,
Stef Mientki
 
M

Marc 'BlackJack' Rintsch

What's the difference between using __init__ and using nothing,
as the examples below.

class cpu:
PC = 4

This is a *class attribute*. It's the same for all instances of `cpu`.
class cpu:
def __init__:
self.PC = 4

This is an *instance attribute* which is set in every instance of `cpu`.

In [8]: class CPU_1:
...: PC = 4
...:

In [9]: class CPU_2:
...: def __init__(self):
...: self.PC = 4
...:

In [10]: a = CPU_1()

In [11]: b = CPU_1()

In [12]: a.PC, b.PC
Out[12]: (4, 4)

In [13]: CPU_1.PC = 3.5

In [14]: a.PC, b.PC
Out[14]: (3.5, 3.5)

In [15]: c = CPU_2()

In [16]: d = CPU_2()

In [17]: c.PC, d.PC
Out[17]: (4, 4)

In [18]: c.PC = 3.5

In [19]: c.PC, d.PC
Out[19]: (3.5, 4)

Ciao,
Marc 'BlackJack' Rintsch
 
S

Stef Mientki

Marc said:
This is a *class attribute*. It's the same for all instances of `cpu`.


This is an *instance attribute* which is set in every instance of `cpu`.
thanks Marc,

Oh so obvious, why didn't I discovered that myself ;-)

cheers,
Stef
 
B

Bruno Desthuilliers

Stef Mientki a écrit :
By convention, ALL_UPPER names have a 'symbolic constant' semantic.
Since Python is a very 'free' language (no attribute access restriction,
no symbolic constants etc), it *strongly* relies on conventions.

thanks Marc,

Oh so obvious, why didn't I discovered that myself ;-)

Perhaps because it may not be that obvious at first sight ?-)

(that is, until you really understand Python's object model, which is
really different from most mainstream OOPLs object models...)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top