3232
3333s1 = stock .Stock ('gg' ,12 ,45 )
3434
35- s1 .__dict__
35+ s1 .__dict__
36+
37+ '''
38+ #### 5.2 Classes and Encapsulation
39+ '''
40+ # public vs private variable
41+ # any attribute with leading _ is private in python but only as style. In python everything is visible.
42+ class person :
43+ def __init__ (self ) -> None :
44+ self ._name = 0
45+
46+ # one can defie accessor methods as like c++, C#; and raise a typeerror exception...
47+
48+ ## defining Properties @property
49+ class XStock :
50+ def __init__ (self ,nm ,sh ,pr ):
51+ self .name = nm
52+ self .shares = sh
53+ self .price = pr
54+ @property
55+ def shares (self ):
56+ return self ._shares # note -- property uses private name with _
57+ @shares .setter
58+ def shares (self ,value ):
59+ if not isinstance (value ,int ):
60+ raise TypeError ('expected int' )
61+ self .shares = value
62+
63+
64+ s1 = XStock ('gg' ,12 ,343.1 )
65+ s1 .name
66+ s1 .shares
67+ s1 .gox = 20
68+ s1 .gox
69+
70+ ## using __slots__ to fix set of attributes belonging to an object; without this, attribute can be added to an object at run time
71+
72+ class YStock :
73+ __slots__ = ('name' ,'_shares' ,'price' )
74+ def __init__ (self ,nm ,sh ,pr ):
75+ self .name = nm
76+ self ._shares = sh
77+ self .price = pr
78+ @property
79+ def shares (self ):
80+ return self ._shares # note -- property uses private name with _
81+ @shares .setter
82+ def shares (self ,value ):
83+ if not isinstance (value ,int ):
84+ raise TypeError ('expected int' )
85+ self .shares = value
86+
87+ s2 = YStock ('gg' ,12 ,343.1 )
88+ s2 .name
89+ s2 .shares
90+ #s2.gox =20 # uncomment - it should fail bocz of slots
91+ s2 .gox
0 commit comments