Python教程

python中的类

本文主要是介绍python中的类,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、Like the means it seems.the meaning of class is create object instantiation.

For instance

class Dog:
    """a simple attempt to simulate a puppy"""
    def __init__(self, name, age):
        """initialize properties name and age"""
        self.name=name
        self.age=age
    def sit(self):
        """simulate dog sit when commanded"""
        print(f"{self.name}is now sitting.")
    def roll_over(self):
        """simulate dog roll over when commanded"""
        print(f"{self.name}roll over!")
my_dog=Dog('Henry',6) #create one class and initialize it
print(f"my dog's name is {my_dog.name}")  
my_dog.sit()  #call method

2、then ,we maybe want to know,if we need revise the value of attributes,what we need to do ?

we can revise it straightly

 my_dog.age=12 print(f"my dog's age is {my_dog.age}") 

or we can revise it by method

def update_age(self,dog_age):
        self.age=dog_age
        print(f"{self.name}is {self.age}.")
        #revise the value of age

3、inherit

someone may want to know why we need inherit.sometimes,we have several function need to created but the functionality is the same,so we can inhreit another class to derease our repeated code.the class be called is father,the other is subclass.

class Car:#subclass must behind the father,and father must in included in file
    def __init__(self, make,model,year):
        self.make=make
        self.model=model
        self.year=year
        self.odometer_reading=0
    def get_discriptive_name(self):
        long_name=f"{self.year} {self.make} {self.model}"
        return long_name.title()
    def read_odometer(self):
        print(f"this car has {self.odoment_reading}miles on it")
    def update_odometer(self,mileage):
        if mileage>=self.odometer_reading:
            self.odometer_reading=mileage
        else:
            print("You can't roll back an odometer")
    def increment_odometer(self,miles):
        self.odometer_reading+=miles
class ElectricCar(Car): #subclass is defined,and father'name must be appointed in parentheses
    def __init__(self, make, model, year):
        super().__init__(make, model, year)#call father's method 
        self.battery_size=75
    def describe_battery(self):
        print(f"This car has a {self.battery_size}-kwh battery.")
my_tesla=ElectricCar('tesla','model s',2019)
print(my_tesla.get_discriptive_name())
my_tesla.describe_battery()

then ,we need to consider one problem that if we need create one class which has been writed already,we do not want to write it again.we maybe recall the same solvement used in function.we can do it like do in function.import the class from module

from Class_2 import Car
my_new_car=Car('audi','a4',2016)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading=23
my_new_car.read_odometer()

thank you for your reading.

 

这篇关于python中的类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!