PI. Accessing attributes

Run Settings
LanguagePython
Language Version
Run Command
from complex import Complex # Creating and instance of Complex class comp = Complex(3, 4) # When you're accessing to unexisting attribute it would be created in instant # locally for this object. comp.new_attr = 14 print comp.new_attr # But also you have the power to remove attributes as soon as you thing you don't # need them. You only need to use `del`syntax for this. del comp.new_attr # The error will be rised here, since we have no `new_attr` anymore. try: print comp.new_attr except AttributeError as e: print "Error: {0}".format(e) # But also you have the power to remove attributes which were here originaly. del comp.im # But that could broke up everything, cause they possibly were used in different # methods of class. For example take a look on the bottom lines, here problem # shall appears with calling `__repr__` method. try: print comp except (AttributeError, KeyError) as e: print "Error: {0}".format(e) # But you always can restore attributes. comp.im = 3 print comp
# Class definition for complex number. More details on Complex number is # here: https://en.wikipedia.org/wiki/Complex_number class Complex: """A complex number is a number that can be expressed in the form a + bi, where a and b are real numbers and i is the imaginary unit, that satisfies the equation i**2=-1.""" # The line above called "the doc string" and would appears in all hints and # __doc__ attribute later. # This is the instance constructor, place to initialize values of exact # instance, please do not confuse it with __new__ which is more complicated # topic of for next level lecture. def __init__(self, re, im=0): self.re = re self.im = im def __repr__(self): # Method to create object representation. return "{re} + {im}i".format(**self.__dict__) # Following line means that name of this method would be used as name of # read-only property (to make writable one there additional syntax) @property def abs(self): return (self.re**2 + self.im**2)**0.5
Editor Settings
Theme
Key bindings
Full width
Lines