You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Instance - the result of using, or calling, a class.
Attribute - the name for a variable that belongs to a class.
Reminders
Instances are responsible for their own attribute values.
Instanciation
classStudent:
name='Benjamin'me=Student() # New instance of the Student classprint(me.name) # You can call the class attributes against the new instance.
Methods in classes, are the actions that the instances of your class can do.
Methods are functions that belong to a class.
Whenever methods are used, they are used by an instance of a class, rather than the actual class itself.
Because of this, methods take at least, one parameter - which represents the instance that's using the method.
By convention, that parameter is always called 'self'.
classStudent:
name='Your name'defpraise(self):
return"You inspire me, {}".format(self.name)
defreassurance(self):
return"Chin up, {}. You'll get it next time!".format(self.name)
deffeedback(self, grade):
ifgrade>50:
returnself.praise()
ifgrade<=50:
returnself.reassurance()
Accepting KWargs as for Attributes
"""Accept keyword arguments and assign them as attributes to predefined attribute variables."""classAnimal:
def__init__(self, **kwargs):
self.species=kwargs.get("species")
self.age=kwargs.get("age")
self.sound=kwargs.get("sound")
Automatically Executed Class Example
"""setattr(object, name, value)This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value.# The string may name an existing attribute or a new attribute.# The function assigns the value to the attribute, provided the object allows it.# For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123."""importrandomclassThief:
sneaky=Truedef__init__(self, name, sneaky=True, **kwargs):
self.name=sneakyself.sneaky=sneakyforkey, valueinkwargs.items():
setattr(self, key, value)
defpickpocket(self):
ifself.sneaky:
returnself.sneakyandbool(random.randint(0, 1))
returnFalsedefhide(self, light_level):
returnself.sneakyandlight_level<10
Allowing users to assign more attributes
"""Defining args allows you to set attributes. However, it does not allow you to pass kwargs in the future unless the attribute is already defined."""classAnimal:
def__init__(self, **kwargs):
self.species=kwargs.get("species")
self.age=kwargs.get("age")
self.sound=kwargs.get("sound")
>>>wolf=Animal(species="Canus Lupus", age=5, sound="howl", color="grey")
>>>wolf.species"Canus Lupus">>>wolf.colorAttributeError
"""Using the setattr() method we can avoid kwarg issues with attributes that are not set prior to passed via and instance."""classAnimal:
def__init__(self, name, **kwargs):
self.name=nameforattribute, valueinkwargs.items():
setattr(self, attribute, value)
Overriding what happens when a new class is instantiated
"""When you user super, you have to call the method name, and it's required arguments too."""classTheif(Character):
sneaky=Truedef__init__(self, name, sneaky=True, **kwargs):
# Sub classes can take different arguments than their parent classes.super().__init__(name, **kwargs)
self.sneaky=sneaky
Special Methods (@property method)
"""With @property you can access the property, but not set an attribute.For example: (small.radius) will return a value. But, you can't set a value like small.radius = 10. You will get an attribute error."""classCircle:
def__init__(self, diameter):
self.diameter=diameter@propertydefradius(self):
returnself.diameter/2small=Circle(10)
print(small.diameter) # 10print(small.radius) # 5