class-类

创建一个类

尝试创建一个简单的类Dog,它包含了属性name、saageary,方法sit、roll_over。具体代码如下(来自Python Crash Course):

class Dog(): # A simple attempt to model a dog.
    empCount = 0
    def __init__(self, name, age): # Initialize name and age attributes.
        self.name = name
        self.age = age
        Dog.empCount = Dog.empCount + 1
    def sit(self): # Simulate a dog sitting in response to a command.
        print(self.name.title() + " is now sitting.")
    def roll_over(self): # Simulate rolling over in response to a command.
        print(self.name.title() + " rolled over!")

my_dog = Dog('willie', 6) # Making an instance from a class.
print("My dog's name is " + my_dog.name.title() + ".")
print("My dog is " + str(my_dog.age) + " years old.")
my_dog.sit()
my_dog.roll_over()
print(Dog.empCount, my_dog.empCount)
----------------------------------终端输出---------------------------------
My dog's name is Willie.
My dog is 6 years old.
Willie is now sitting.
Willie rolled over!
1 1
  • 可以看到变量empCount在类、类的实例间共享,可由类、实例调用,称作xx变量;
  • self代表类的实例(instance),在实例调用类中的方法时(如my_dog.sit()),实例本身(即ZhangSan)自动传递给self,括号中无额外参数;
  • self.name和self.age可被Dog类定义中的各个方法调用,也可被类的实例访问,如my_dog.age;
  • 类的每个方法的定义,均要传递self;

类的继承

在父类Dog的基础上,新定义一个Labrador类,代码如下:

class Dog(): # A simple attempt to model a dog.
    empCount = 0
    def __init__(self, name, age): # Initialize name and age attributes.
        self.name = name
        self.age = age
        Dog.empCount = Dog.empCount + 1
    def sit(self): # Simulate a dog sitting in response to a command.
        print(self.name.title() + " is now sitting.")
    def roll_over(self): # Simulate rolling over in response to a command.
        print(self.name.title() + " rolled over!")

class Labrador(Dog): # model a Labrador this time
    def __init__(self, name , age, sex): # 继承父类的name、age属性,新增sex属性(性别!!)
        super().__init__(name, age) # 采用super()方法来继承父类的属性定义
        self.sex = sex # 新增的属性需要重新定义
    def printsex(self):
        print('My dog is {}'.format(self.sex))
    def roll_over(self): # Simulate rolling over in response to a command.
        print(self.name.title() + " rolled over twice!")


my_dog = Dog('willie', 5)
my_dog2 = Labrador('Tom', 5, 'male')
print("My dog's name is " + my_dog2.name.title() + ".")
print("My dog is " + str(my_dog2.age) + " years old.")
my_dog2.printsex()
my_dog2.sit()
my_dog2.roll_over()
print(Dog.empCount, my_dog2.empCount)
----------------------------------终端输出---------------------------------
My dog's name is Tom.
My dog is 5 years old.
My dog is male
Tom is now sitting.
Tom rolled over twice!
2 2
  • 可见empCount 在父类、子类间也是共享的;
  • 父类的属性必须全部继承,可通过super()方法简化定义;
  • 子类中可以定义新的属性,新增的属性要通过self.attrname = attr定义;
  • 子类中可以对父类的方法进行重新定义,如roll_over()方法,也可以增加新的方法。

类和实例的命名规则

  1. 类的命名采用CamelCaps,即对类名的每个有意义的词的首字母大写,如ElectricCar;
  2. 类名不要用下划线,无论在类名起始位置还是中间位置;
  3. 实例采用小写字母。

你可能感兴趣的:(class-类)