Object-Oriented Programming

¡Supera tus tareas y exámenes ahora con Quizwiz!

Calling attributes of an instance error

Trying to access an attribute of an instance that isn't defined causes an AttributeError. This also applies when you call an undefined method. Example: class Rectangle: def __init__(self, width, height): self.width = width self.height = height rect = Rectangle(7, 8) print(rect.color) Result: >>> AttributeError: 'Rectangle' object has no attribute 'color' >>>

Inheritance subclass

A class that inherits from another class is called a subclass. A class that is inherited from is called a superclass. If a class inherits from another with the same attributes or methods, it overrides them. class Wolf: def __init__(self, name, color): self.name = name self.color = color def bark(self): print("Grr...") class Dog(Wolf): def bark(self): print("Woof") husky = Dog("Max", "grey") husky.bark() Result: >>> Woof >>> In the example above, Wolf is the superclass, Dog is the subclass.

Classes

Another very popular paradigm is object-oriented programming (OOP). Objects are created using classes, which are actually the focal point of OOP. The class describes what the object will be, but is separate from the object itself. In other words, a class can be described as an object's blueprint, description, or definition. You can use the same class as a blueprint for creating multiple different objects. Classes are created using the keyword class and an indented block, which contains class methods (which are functions). Below is an example of a simple class and its objects. class Cat: def __init__(self, color, legs): self.color = color self.legs = legs felix = Cat("ginger", 4) rover = Cat("dog-colored", 4) stumpy = Cat("brown", 3) This code defines a class named Cat, which has two attributes: color and legs. Then the class is used to create 3 separate objects of that class. Tap Continue to learn more!

Part 2

Classes can also have class attributes, created by assigning variables within the body of the class. These can be accessed either from instances of the class, or the class itself. Example: class Dog: legs = 4 def __init__(self, name, color): self.name = name self.color = color fido = Dog("Fido", "brown") print(fido.legs) print(Dog.legs) Result: C >>> 4 4 >>> Class attributes are shared by all instances of the class.

Methods (The good part of it )

Classes can have other methods defined to add functionality to them. Remember, that all methods must have self as their first parameter. These methods are accessed using the same dot syntax as attributes. Example: class Dog: def __init__(self, name, color): self.name = name self.color = color def bark(self): print("Woof!") fido = Dog("Fido", "brown") print(fido.name) fido.bark() Result: >>> Fido Woof! >>>

Inheritance times 2, lol

Inheritance can also be indirect. One class can inherit from another, and that class can inherit from a third class. Example: class A: def method(self): print("A method") class B(A): def another_method(self): print("B method") class C(B): def third_method(self): print("C method") c = C() c.method() c.another_method() c.third_method() Result: >>> A method B method C method >>> However, circular inheritance is not possible.

Inheritance

Inheritance provides a way to share functionality between classes. Imagine several classes, Cat, Dog, Rabbit and so on. Although they may differ in some ways (only Dog might have the method bark), they are likely to be similar in others (all having the attributes color and name). This similarity can be expressed by making them all inherit from a superclass Animal, which contains the shared functionality. To inherit a class from another class, put the superclass name in parentheses after the class name. Example: class Animal: def __init__(self, name, color): self.name = name self.color = color class Cat(Animal): def purr(self): print("Purr...") class Dog(Animal): def bark(self): print("Woof!") fido = Dog("Fido", "brown") print(fido.color) fido.bark() Result: >>> brown Woof! >>>

Magic Methods

More magic methods for common operators: __sub__ for - __mul__ for * __truediv__ for / __floordiv__ for // __mod__ for % __pow__ for ** __and__ for & __xor__ for ^ __or__ for | The expression x + y is translated into x.__add__(y). However, if x hasn't implemented __add__, and x and y are of different types, then y.__radd__(x) is called. There are equivalent r methods for all magic methods just mentioned. Example: class SpecialString: def __init__(self, cont): self.cont = cont def __truediv__(self, other): line = "=" * len(other.cont) return "\n".join([self.cont, line, other.cont]) spam = SpecialString("spam") hello = SpecialString("Hello world!") print(spam / hello) Result: >>> spam ============ Hello world! >>> In the example above, we defined the division operation for our class SpecialString.

_init_

The __init__ method is the most important method in a class. This is called when an instance (object) of the class is created, using the class name as a function. All methods must have self as their first parameter, although it isn't explicitly passed, Python adds the self argument to the list for you; you do not need to include it when you call the methods. Within a method definition, self refers to the instance calling the method. Instances of a class have attributes, which are pieces of data associated with them. In this example, Cat instances have attributes color and legs. These can be accessed by putting a dot, and the attribute name after an instance. In an __init__ method, self.attribute can therefore be used to set the initial value of an instance's attributes. Example: class Cat: def __init__(self, color, legs): self.color = color self.legs = legs felix = Cat("ginger", 4) print(felix.color) Result: >>> ginger >>> In the example above, the __init__ method takes two arguments and assigns them to the object's attributes. The __init__ method is called the class constructor.

Inheritance (super duper class)

The function super is a useful inheritance-related function that refers to the parent class. It can be used to find the method with a certain name in an object's superclass. Example: class A: def spam(self): print(1) class B(A): def spam(self): print(2) super().spam() B().spam() Result: >>> 2 1 >>> super().spam() calls the spam method of the superclass.


Conjuntos de estudio relacionados

study plan macroecon chapters 7 and 8

View Set

Principles of Coaching Final Part 4

View Set

3: Developing Project Schedules and Budgets

View Set

CH 15 Defense Mechanisms of the Gingiva

View Set

Section 3 - The Story of the Crusades

View Set

Security+ Cert Exam Objectives SYO-601

View Set