[course]08 —— 面向对象编程03

1. Type Testing (type, isinstance)

class A(object): pass
a = A()
print(type(a))           # A (technically, < class '__main__.A' >)
print(type(a) == A)      # True
print(isinstance(a, A))  # True

2. Special Methods

1. Equality Testing (eq)

1.The problem:** Shouldn't a1 == a2?

class A(object):
    def __init__(self, x):
        self.x = x
a1 = A(5)
a2 = A(5)
print(a1 == a2)  # False!

2. The partial solution: eq

The eq method tells Python how to evalute the equality of two objects.

3.A better solution:

Here we don't crash on unexpected types of other:

2. Converting to Strings (str and repr)

1. The problem:

Just like with ==, Python doesn't really know how to print our objects...

2. The partial solution: str

The __str__ method tells Python how to convert the object to a string, but it is not used in some cases (such as when the object is in a list):

3. The better solution: repr

The __repr__ method is used inside lists (and other places):

3. Using in Sets and Dictionaries (hash and eq)

The problem: Objects do not seem to hash right by default:

And that produces this unfortunate situation:

The solution: hash and eq

The __hash__ method tells Python how to hash the object. The properties you choose to hash on should be immutable types and should never change (so hash(obj) is immutable).

A better (more generalizable) solution You can define the method getHashables that packages the things you want to hash into a tuple, and then you can use a more generic approach to __hash__:

4. Fraction Example

3. Class-Level Features

1. Class Attributes

Class Attributes are values specified in a class that are shared by all instances of that class! We can access class attributes from any instance of that class, but changing those values anywhere changes them for every instance.

2. Static Methods

Static Methods in a class can be called directly without necessarily making and/or referencing a specific object.

3. Playing Card Demo

4. Inheritance

A subclass inherits all the methods from its superclass, and then can add or modify methods.

1. Specifying a Superclass

2. Overriding methods

We can change a method's behavior in a subclass by overriding it.

3. isinstance vs type in inherited classes

4. Monster Demo

5. Additional Reading

For more on these topics, and many additional OOP-related topics, check the following links: https://docs.python.org/3/tutorial/classes.html https://docs.python.org/3/reference/datamodel.html

Last updated

Was this helpful?