Книга: Practical Programming, Fourth Edition
Назад: Chapter 7: Using Methods
Дальше: Calling Methods

Modules, Classes, and Methods

Classes are like modules, but with methods

In , you saw that a module is a kind of object, one that can contain functions and other variables. There is another kind of object that is similar to a module: a class. You’ve been using classes all along, probably without realizing it: a class is how Python represents a type.

You may have called built-in function help on int, float, bool, or str. Let’s do that now with str (note that the first line indicates it’s a class):

 >>>​​ ​​help(str)
 Help on class str in module builtins:
 
 class str(object)
  | str(object='') -> str
  | str(bytes_or_buffer[, encoding[, errors]]) -> str
  |
  | Create a new string object from the given object. If encoding or
  | errors is specified, then the object must expose a data buffer
  | that will be decoded using the given encoding and error handler.
  | Otherwise, returns the result of object.__str__() (if defined)
  | or repr(object).
  | encoding defaults to 'utf-8'.
  | errors defaults to 'strict'.
  |
  | Methods defined here:
  |
  | __add__(self, value, /)
  | Return self+value.
  |
  | __contains__(self, key, /)
  | Return bool(key in self).
 
 [Lots of other names with leading and trailing underscores not shown here.]
 
  | capitalize(self, /)
  | Return a capitalized version of the string.
  |
  | More specifically, make the first character have upper case and the
  | rest lower case.
  |
  | casefold(self, /)
  | Return a version of the string suitable for caseless comparisons.
  |
  | center(self, width, fillchar=' ', /)
  | Return a centered string of length width.
  |
  | Padding is done using the specified fill character (default is a
  | space).
  |
  | count(self, sub[, start[, end]], /)
  | Return the number of non-overlapping occurrences of substring sub
  | in string S[start:end].
 
 [There are many more of these as well.]

Near the top of this documentation is the description of the str function:

 | str(bytes_or_buffer[, encoding[, errors]]) -> str
 |
 | Create a new string object from the given object.

It explains how to use str as a function: you can call it to create a string. For example, str(17) creates the string ’17’.

Functions that create new objects are called constructors. Function str is a constructor for strings. Functions int, float, and bool are constructors for the namesake data types. You will learn more about constructors in Chapter 14, .

Назад: Chapter 7: Using Methods
Дальше: Calling Methods