objects in python
- At its simplest, an object is some code plus data structures that is smaller than a whole program
- Defining a function allows us to store a bit of code and give it a name and then later invoke that code using the name of the function.
- An object can contain a number of functions (which we call “methods”) as well as data that is used by those functions. We call data items that are part of the object “attributes”
- We use the class keyword to define the data and code that will make up each of the objects
- . The class keyword includes the name of the class and begins an indented block of code where we include the attributes (data) and methods (code).
class PartyAnimal:
x = 0
def party(self) :
self.x = self.x + 1
print("So far",self.x)
an = PartyAnimal()
an.party()
an.party()
an.party()
PartyAnimal.party(an)
Each method looks like a function, starting with the def keyword and consisting of an indented block of code. This example has one attribute (x) and one method
(party). The methods have a special first parameter that we name by convention self.