Constructors and Destructors
To help you automate the creation and deletion of objects, you can easily override two default methods: __init__
and __del__
. These are the methods called by Python when a class is being instantiated and freed, known as the constructor and destructor, respectively.
Having a custom constructor is great for when you need to accept a set of parameters for each object being created. For example, you might want each dog to have its own name on creation, and you could implement that with this code:
class Dog(object): def __init__(self, name): self.name = namefluffy = Dog("Fluffy")print fluffy.name
If you do not provide a name parameter when creating the Dog
object, Python reports ...
Get Ubuntu Unleashed 2014 Edition: Covering 13.10 and 14.04,Ninth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.