Python - Classes and Oop Basics

Python - Classes and OOP Basics

Functions are very different from classes. It looks like you took a function and just changed the def to class. I guess that mostly works in your case, but it's not how classes are supposed to go.

Classes contain functions (methods) and data. For example, you have a ball:

class Ball(object):
# __init__ is a special method called whenever you try to make
# an instance of a class. As you heard, it initializes the object.
# Here, we'll initialize some of the data.
def __init__(self):
# Let's add some data to the [instance of the] class.
self.position = (100, 100)
self.velocity = (0, 0)

# We can also add our own functions. When our ball bounces,
# its vertical velocity will be negated. (no gravity here!)
def bounce(self):
self.velocity = (self.velocity[0], -self.velocity[1])

Now we have a Ball class. How can we use it?

>>> ball1 = Ball()
>>> ball1
<Ball object at ...>

It doesn't look very useful. The data is where it could be useful:

>>> ball1.position
(100, 100)
>>> ball1.velocity
(0, 0)
>>> ball1.position = (200, 100)
>>> ball1.position
(200, 100)

Alright, cool, but what's the advantage over a global variable? If you have another Ball instance, it will remain independent:

>>> ball2 = Ball()
>>> ball2.velocity = (5, 10)
>>> ball2.position
(100, 100)
>>> ball2.velocity
(5, 10)

And ball1 remains independent:

>>> ball1.velocity
(0, 0)

Now what about that bounce method (function in a class) we defined?

>>> ball2.bounce()
>>> ball2.velocity
(5, -10)

The bounce method caused it to modify the velocity data of itself. Again, ball1 was not touched:

>>> ball1.velocity

Application

A ball is neat and all, but most people aren't simulating that. You're making a game. Let's think of what kinds of things we have:

  • A room is the most obvious thing we could have.

So let's make a room. Rooms have names, so we'll have some data to store that:

class Room(object):
# Note that we're taking an argument besides self, here.
def __init__(self, name):
self.name = name # Set the room's name to the name we got.

And let's make an instance of it:

>>> white_room = Room("White Room")
>>> white_room.name
'White Room'

Spiffy. This turns out not to be all that useful if you want different rooms to have different functionality, though, so let's make a subclass. A subclass inherits all functionality from its superclass, but you can add more functionality or override the superclass's functionality.

Let's think about what we want to do with rooms:


We want to interact with rooms.

And how do we do that?


The user types in a line of text that gets responded to.

How it's responded do depends on the room, so let's make the room handle that with a method called interact:

class WhiteRoom(Room):  # A white room is a kind of room.
def __init__(self):
# All white rooms have names of 'White Room'.
self.name = 'White Room'

def interact(self, line):
if 'test' in line:
print "'Test' to you, too!"

Now let's try interacting with it:

>>> white_room = WhiteRoom()  # WhiteRoom's __init__ doesn't take an argument (even though its superclass's __init__ does; we overrode the superclass's __init__)
>>> white_room.interact('test')
'Test' to you, too!

Your original example featured moving between rooms. Let's use a global variable called current_room to track which room we're in.1 Let's also make a red room.

1. There's better options besides global variables here, but I'm going to use one for simplicity.

class RedRoom(Room):  # A red room is also a kind of room.
def __init__(self):
self.name = 'Red Room'

def interact(self, line):
global current_room, white_room
if 'white' in line:
# We could create a new WhiteRoom, but then it
# would lose its data (if it had any) after moving
# out of it and into it again.
current_room = white_room

Now let's try that:

>>> red_room = RedRoom()
>>> current_room = red_room
>>> current_room.name
'Red Room'
>>> current_room.interact('go to white room')
>>> current_room.name
'White Room'

Exercise for the reader: Add code to WhiteRoom's interact that allows you to go back to the red room.

Now that we have everything working, let's put it all together. With our new name data on all rooms, we can also show the current room in the prompt!

def play_game():
global current_room
while True:
line = raw_input(current_room.name + '> ')
current_room.interact(line)

You might also want to make a function to reset the game:

def reset_game():
global current_room, white_room, red_room
white_room = WhiteRoom()
red_room = RedRoom()
current_room = white_room

Put all of the class definitions and these functions into a file and you can play it at the prompt like this (assuming they're in mygame.py):

>>> import mygame
>>> mygame.reset_game()
>>> mygame.play_game()
White Room> test
'Test' to you, too!
White Room> go to red room
Red Room> go to white room
White Room>

To be able to play the game just by running the Python script, you can add this at the bottom:

def main():
reset_game()
play_game()

if __name__ == '__main__': # If we're running as a script...
main()

And that's a basic introduction to classes and how to apply it to your situation.

Python 3 - Object Oriented Programming - Classes & Functions

You can re-use a class and create more instances from one template. The Player and Enemy class have a identical functionality. You can create different instances from one class simply using the __init__ method with different arguments.

import random
import time as t

class Player:
def __init__(self, hit_points, sides):
self.hit_points = hit_points
self.sides = sides

def take_hit(self):
self.hit_points -= 2

def roll(self):
return random.randint(1, self.sides)

p = Player(hit_points=10, sides=6)
e = Player(hit_points=8, sides=6)

battle = 1

while battle != 0:
human = p.roll()
print("Your hit score: ",human)
enemy = e.roll()
print("Enemy hit score: ",enemy)
if human > enemy:
e.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)

elif human < enemy:
p.take_hit()
print("Your hit points remaining: ",p.hit_points)
print("Enemy points remaining: ", e.hit_points)

t.sleep(2)

if e.hit_points == 0 or p.hit_points == 0:
battle = 0

Python: OOP Tutorial 1: Classes and instances: How to use self?

There is no difference if u use self.first or first inside the __init__ method since self.first also points to the same variable, viz, first.
Making a variable an attribute of self just makes it an instance variable and allows u to access it anywhere inside your class

When should I be using classes in Python?

Classes are the pillar of Object Oriented Programming. OOP is highly concerned with code organization, reusability, and encapsulation.

First, a disclaimer: OOP is partially in contrast to Functional Programming, which is a different paradigm used a lot in Python. Not everyone who programs in Python (or surely most languages) uses OOP. You can do a lot in Java 8 that isn't very Object Oriented. If you don't want to use OOP, then don't. If you're just writing one-off scripts to process data that you'll never use again, then keep writing the way you are.

However, there are a lot of reasons to use OOP.

Some reasons:

  • Organization:
    OOP defines well known and standard ways of describing and defining both data and procedure in code. Both data and procedure can be stored at varying levels of definition (in different classes), and there are standard ways about talking about these definitions. That is, if you use OOP in a standard way, it will help your later self and others understand, edit, and use your code. Also, instead of using a complex, arbitrary data storage mechanism (dicts of dicts or lists or dicts or lists of dicts of sets, or whatever), you can name pieces of data structures and conveniently refer to them.

  • State: OOP helps you define and keep track of state. For instance, in a classic example, if you're creating a program that processes students (for instance, a grade program), you can keep all the info you need about them in one spot (name, age, gender, grade level, courses, grades, teachers, peers, diet, special needs, etc.), and this data is persisted as long as the object is alive, and is easily accessible. In contrast, in pure functional programming, state is never mutated in place.

  • Encapsulation:
    With encapsulation, procedure and data are stored together. Methods (an OOP term for functions) are defined right alongside the data that they operate on and produce. In a language like Java that allows for access control, or in Python, depending upon how you describe your public API, this means that methods and data can be hidden from the user. What this means is that if you need or want to change code, you can do whatever you want to the implementation of the code, but keep the public APIs the same.

  • Inheritance:
    Inheritance allows you to define data and procedure in one place (in one class), and then override or extend that functionality later. For instance, in Python, I often see people creating subclasses of the dict class in order to add additional functionality. A common change is overriding the method that throws an exception when a key is requested from a dictionary that doesn't exist to give a default value based on an unknown key. This allows you to extend your own code now or later, allow others to extend your code, and allows you to extend other people's code.

  • Reusability: All of these reasons and others allow for greater reusability of code. Object oriented code allows you to write solid (tested) code once, and then reuse over and over. If you need to tweak something for your specific use case, you can inherit from an existing class and overwrite the existing behavior. If you need to change something, you can change it all while maintaining the existing public method signatures, and no one is the wiser (hopefully).

Again, there are several reasons not to use OOP, and you don't need to. But luckily with a language like Python, you can use just a little bit or a lot, it's up to you.

An example of the student use case (no guarantee on code quality, just an example):

Object Oriented

class Student(object):
def __init__(self, name, age, gender, level, grades=None):
self.name = name
self.age = age
self.gender = gender
self.level = level
self.grades = grades or {}

def setGrade(self, course, grade):
self.grades[course] = grade

def getGrade(self, course):
return self.grades[course]

def getGPA(self):
return sum(self.grades.values())/len(self.grades)

# Define some students
john = Student("John", 12, "male", 6, {"math":3.3})
jane = Student("Jane", 12, "female", 6, {"math":3.5})

# Now we can get to the grades easily
print(john.getGPA())
print(jane.getGPA())

Standard Dict

def calculateGPA(gradeDict):
return sum(gradeDict.values())/len(gradeDict)

students = {}
# We can set the keys to variables so we might minimize typos
name, age, gender, level, grades = "name", "age", "gender", "level", "grades"
john, jane = "john", "jane"
math = "math"
students[john] = {}
students[john][age] = 12
students[john][gender] = "male"
students[john][level] = 6
students[john][grades] = {math:3.3}

students[jane] = {}
students[jane][age] = 12
students[jane][gender] = "female"
students[jane][level] = 6
students[jane][grades] = {math:3.5}

# At this point, we need to remember who the students are and where the grades are stored. Not a huge deal, but avoided by OOP.
print(calculateGPA(students[john][grades]))
print(calculateGPA(students[jane][grades]))

Python 3.0 Classes and OOP basics, with UML model?

Im not too sure what you're question is, but I know what your friend means by "you didn't create a second object for necklaces"

You initiated store_merchandise as a merchandise object, then continually use set_x(x) to change its property.

Instead, you should instantiate a new instance of the object by initiating another variable, not changing the original ones properties. This can be done in the same you initiated the first one, but using a different name.

store_merchandise = merchandise.Merchandise('hammer',10,14.95) //initiate the first object properties 'hammer',12,14.95store_merchandise2 = merchandise.Merchandise('necklaces',6,799.99) //initiate the second object with properties 'necklaces',6,799.99

Basic object oriented implementation in python

  1. The variables outside the __init__ method are called class variables and inside the method are called instance variables. This will answer your question: What is the difference between class and instance variables?
  2. In python, all variables are public so you don't need getter setter methods unless you want them in order to protect the variable value or you want to process / validate the value before setting / getting the variable. More is here: What's the pythonic way to use getters and setters?
  3. There is a design flaw in your code. The class Node represents one node. So, if I had to use this implementation I would expect all methods of Node would be in one node scope including display. You implemented Node.display() to display the whole linked list and therefor you "don't need" a LinkedList class. I think it is better to add a LinkedList class with a head variable to hold the first node and a display method just like you wrote to make it more intuitive.

Need help understanding classes in Python

Welcome. What are you trying to accomplish?

You could probably use only functions/coroutines, depending on what you try to do. In fact, for plain calculations, I find it sometimes easier that way.

Python support both paradigms (functional/object oriented).

Object oriented programming is a good way to model real life objects. For instance, let s say you are writing a game that has many characters, you could create a Character class which would be your blueprint for all of them.

Even better, you could look at a concept called composition, and mix and match objects to create a certain concrete instance. That way, a Building class could hold pointers to 20 concrete instances of an Appartment class, an instance of your SwimmingPool class and so on.

What are metaclasses in Python?

A metaclass is the class of a class. A class defines how an instance of the class (i.e. an object) behaves while a metaclass defines how a class behaves. A class is an instance of a metaclass.

While in Python you can use arbitrary callables for metaclasses (like Jerub shows), the better approach is to make it an actual class itself. type is the usual metaclass in Python. type is itself a class, and it is its own type. You won't be able to recreate something like type purely in Python, but Python cheats a little. To create your own metaclass in Python you really just want to subclass type.

A metaclass is most commonly used as a class-factory. When you create an object by calling the class, Python creates a new class (when it executes the 'class' statement) by calling the metaclass. Combined with the normal __init__ and __new__ methods, metaclasses therefore allow you to do 'extra things' when creating a class, like registering the new class with some registry or replace the class with something else entirely.

When the class statement is executed, Python first executes the body of the class statement as a normal block of code. The resulting namespace (a dict) holds the attributes of the class-to-be. The metaclass is determined by looking at the baseclasses of the class-to-be (metaclasses are inherited), at the __metaclass__ attribute of the class-to-be (if any) or the __metaclass__ global variable. The metaclass is then called with the name, bases and attributes of the class to instantiate it.

However, metaclasses actually define the type of a class, not just a factory for it, so you can do much more with them. You can, for instance, define normal methods on the metaclass. These metaclass-methods are like classmethods in that they can be called on the class without an instance, but they are also not like classmethods in that they cannot be called on an instance of the class. type.__subclasses__() is an example of a method on the type metaclass. You can also define the normal 'magic' methods, like __add__, __iter__ and __getattr__, to implement or change how the class behaves.

Here's an aggregated example of the bits and pieces:

def make_hook(f):
"""Decorator to turn 'foo' method into '__foo__'"""
f.is_hook = 1
return f

class MyType(type):
def __new__(mcls, name, bases, attrs):

if name.startswith('None'):
return None

# Go over attributes and see if they should be renamed.
newattrs = {}
for attrname, attrvalue in attrs.iteritems():
if getattr(attrvalue, 'is_hook', 0):
newattrs['__%s__' % attrname] = attrvalue
else:
newattrs[attrname] = attrvalue

return super(MyType, mcls).__new__(mcls, name, bases, newattrs)

def __init__(self, name, bases, attrs):
super(MyType, self).__init__(name, bases, attrs)

# classregistry.register(self, self.interfaces)
print "Would register class %s now." % self

def __add__(self, other):
class AutoClass(self, other):
pass
return AutoClass
# Alternatively, to autogenerate the classname as well as the class:
# return type(self.__name__ + other.__name__, (self, other), {})

def unregister(self):
# classregistry.unregister(self)
print "Would unregister class %s now." % self

class MyObject:
__metaclass__ = MyType

class NoneSample(MyObject):
pass

# Will print "NoneType None"
print type(NoneSample), repr(NoneSample)

class Example(MyObject):
def __init__(self, value):
self.value = value
@make_hook
def add(self, other):
return self.__class__(self.value + other.value)

# Will unregister the class
Example.unregister()

inst = Example(10)
# Will fail with an AttributeError
#inst.unregister()

print inst + inst
class Sibling(MyObject):
pass

ExampleSibling = Example + Sibling
# ExampleSibling is now a subclass of both Example and Sibling (with no
# content of its own) although it will believe it's called 'AutoClass'
print ExampleSibling
print ExampleSibling.__mro__

Python class input argument

>>> class name(object):
... def __init__(self, name):
... self.name = name
...
>>> person1 = name("jean")
>>> person2 = name("dean")
>>> person1.name
'jean'
>>> person2.name
'dean'
>>>


Related Topics



Leave a reply



Submit