class-类

2018-10-11  本文已影响0人  Drycountry233

创建一个类

尝试创建一个简单的类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

类的继承

在父类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

类和实例的命名规则

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

猜你喜欢

热点阅读