Python类和面向对象编程

本篇笔记学习自:Improve Your Python: Python Classes and Object Oriented Programming

what is a class? Simply a logical grouping of data and functions (the latter of which are frequently referred to as "methods" when defined within a class).

Classes can be thought of as blueprints for creating objects.

So what's with that self parameter to all of the Customer methods? What is it? Why, it's the instance, of course!
jeff.withdraw(100.0) is just shorthand for Customer.withdraw(jeff, 100.0), which is perfectly valid (if not often seen) code.

  • init
class Customer(object):
    """A customer of ABC Bank with a checking account. Customers have the
    following properties:

    Attributes:
        name: A string representing the customer's name.
        balance: A float tracking the current balance of the customer's account.
    """

    def __init__(self, name):
        """Return a Customer object whose name is *name*.""" 
        self.name = name

    def set_balance(self, balance=0.0):
        """Set the customer's starting balance."""
        self.balance = balance

    def withdraw(self, amount):
        """Return the balance remaining after withdrawing *amount*
        dollars."""
        if amount > self.balance:
            raise RuntimeError('Amount greater than available balance.')
        self.balance -= amount
        return self.balance

    def deposit(self, amount):
        """Return the balance remaining after depositing *amount*
        dollars."""
        self.balance += amount
        return self.balance

在上面的类中,我们需要先调用set_balance(设置账户金额)再调用其他的方法(存取金额),这种情况叫做对象没有被完全初始化,我们应该将要初始化的所有遍历都放在init,这样才不会出现一些因为调用顺序出现的麻烦。

  • 静态方法:
    对象中的方法调用的时候需要对象实例作为参数,静态方法则不用。
class Car(object):
    ...
    @staticmethod
    def make_car_sound():
        print 'VRooooommmm!'
  • 类方法
class Vehicle(object):
    ...
    @classmethod
    def is_motorcycle(cls):
        return cls.wheels == 2

......

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容