[course]07 —— 面向对象编程02

1. Writing Classes

# Create our own class:
class Dog(object):
    # a class must have a body, even if it does nothing, so we will
    # use 'pass' for now...
    pass

# Create instances of our class:
d1 = Dog()
d2 = Dog()

# Verify the type of these instances:
print(type(d1))             # Dog (actually, class '__main__.Dog')
print(isinstance(d2, Dog))  # True

# Set and get properties (aka 'fields' or 'attributes') of these instances:
d1.name = 'Dot'
d1.age = 4
d2.name = 'Elf'
d2.age = 3
print(d1.name, d1.age) # Dot 4
print(d2.name, d2.age) # Elf 3

2. Writing Constructors

  • Constructors let us pre-load our new instances with properties.

  • This lets us write code like so:

  • We would like to write our constructor like this:

  • Unfortunately, Python does not use 'constructor' as the constructor name. Instead, it uses 'init' (sorry about that), like so:

  • Also, unfortunately, while we could name the instance 'dog' like we did, standard convention requires that we name it 'self' (sorry again), like so:

  • Finally, we place this method inside the class and we have a constructor that we can use, like so:

5. Writing Methods

  • Start with a function:

  • Turn the function into a method, and the function call into a method call, like this:

  • Finally, use self, as convention requires:

  • Methods can take additional parameters, like so:

  • Methods can also set properties, like so:

6. Advantages of Classes and Methods

  • Encapsulation

    • Organizes code

      A class includes the data and methods for that class.

    • Promotes intuitive design

      Well-designed classes should be intuitive, so the data and methods in the class match commonsense expectations.

    • Restricts access

      • len is a function, so we can call len(True) (which crashes)

      • upper is a method on strings but not booleans, so we cannot even call True.upper()

  • Polymorphism

    Polymorphism: the same method name can run different code based on type, like so:

Last updated

Was this helpful?