转载请注明出处: http://blog.csdn.net/cxsydjn/article/details/71303658
The note focuses on Classes, which are a crucial part of object-oriented programming (OOP). In this lesson, we'll explain what classes are, why they're important, and how to use them effectively.
Python notes of open courses @Codecademy.
Class Basics
Why Use Classes?
Python is an object-oriented programming (OOP) language, which means it manipulates programming constructs called objects.
You can think of an object as a single data structure that contains data as well as functions; functions of objects are called methods.
A class is just a way of organizing and producing objects with similar attributes and methods.
Class Syntax
-
A basic class consists only of the
classkeyword, the name of the class, and the class from which the new class inherits in parentheses.class NewClass(object):- This gives them the powers and abilities of a Python object. By convention, user-defined Python class names start with a capital letter.
-
__init__()- This function is required for classes, and it's used to initialize the objects it creates.
- It always takes at least one argument,
self, that refers to the object being created.
-
self- Python will use the first parameter that
__init__()receives to refer to the object being created. - This is why it's often called self, since this parameter gives the object being created its identity.
- Python will use the first parameter that
-
Dot Notation
- To assign a variable to the class (creating a member variable), we use dot notation,
self.new_variable = new_variable. - We can access attributes of our objects using dot notation, such as
self.attribute.
- To assign a variable to the class (creating a member variable), we use dot notation,
Example
By Now, We Have:
# Class definition
class Animal(object):
"""Makes cute animals."""
# For initializing our instance objects
def __init__(self, name, age, is_hungry):
self.name = name
self.age = age
self.is_hungry = is_hungry
# Note that self is only used in the __init__() function definition;
# we don't need to pass it to our instance objects.
zebra = Animal("Jeffrey", 2, True)
print zebra.name, zebra.age, zebra.is_hungry
Member Variables and Functions
Class Scope
Another important aspect of Python classes is scope. The scope of a variable/function is the context in which it's visible to the program.
Not all variables are accessible to all parts of a Python program at all times. When dealing with classes, you can have variables/functions that are:
- available everywhere (global variables),
- only available to members of a certain class (member variables)
- only available to particular instances of a class (instance variables).
Inheritance
Inheritance is the process by which one class takes on the attributes and methods of another, and it's used to express an is-a relationship. For example, a Panda is a bear, so a Panda class could inherit from a Bear class.
Inheritance Syntax
-
class DerivedClass(BaseClass):- where
DerivedClassis the new class you're making andBaseClassis the class from which that new class inherits.
- where
-
Override
-
Sometimes you'll want one class that inherits from another to not only take on the methods and attributes of its parent, but to override one or more of them.
-
Rather than have a separate
greet_underling methodfor our CEO, we override (or re-create) thegreetmethod on top of the baseEmployee.greetmethod. This way, we don't need to know what type of Employee we have before we greet another Employee.class Employee(object):
def init(self, name):
self.name = name
def greet(self, other):
print "Hello, %s" % other.nameclass CEO(Employee): def greet(self, other): print "Get back to work, %s!" % other.name ceo = CEO("Emily") emp = Employee("Steve") emp.greet(ceo) # Hello, Emily ceo.greet(emp) # Get back to work, Steve! ``` -
-
supercall-
In the flip side, sometimes you'll be working with a derived class (or subclass) and realize that you've overwritten a method or attribute defined in that class' base class (also called a parent or superclass) that you actually need. Have no fear! You can directly access the attributes or methods of a superclass with Python's built-in
supercall. -
The syntax looks like this:
class Derived(Base): def m(self): return super(Derived, self).m()
Where `m()` is a method from the base class. -
-
__repr__()-
It is short for representation; by providing a return value in this method, we can tell Python how to represent an object of our class (for instance, when using a
printstatement).class Point3D(object):
def init(self, x, y, z):
self.x = x
self.y = y
self.z = zdef __repr__(self): return "(%d, %d, %d)" % (self.x, self.y, self.z) my_point = Point3D(1,2,3) print my_point ``` -
Example
By Now, We Have A Comprehensive Example:
# 1. Creating a class
class Car(object):
# 3. Creating member variables
condition = "new"
# 5. Initializing a class
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
# 6. Creating class methods
def display_car(self):
# 7. Referring to member variables
return "This is a " + self.color + " " + self.model + " with "+ str(self.mpg) + " MPG."
def drive_car(self):
# 8. Modifying member variables
self.condition = "used"
return self.condition
# 9. Inheritance
class ElectricCar(Car):
def __init__(self, model, color, mpg, battery_type):
self.model = model
self.color = color
self.mpg = mpg
self.battery_type = battery_type
# 10. Overriding methods
def drive_car(self):
self.condition = "like new"
return self.condition
# 2. Creating an instance of a class
my_car = Car("DeLorean", "silver", 88)
# 4. Calling class member variables
print my_car.condition
my_car.drive_car()
print my_car.condition
my_car = ElectricCar("DeLorean", "silver", 88, "molten salt")
print my_car.condition
my_car.drive_car()
print my_car.condition









网友评论