zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python任意参数的数量/预习课python基础

Python基础 参数 数量 任意
2023-09-11 14:14:27 时间

什么是面向对象编程(OOP)?
面向对象编程(Object-oriented Programming,简称OOP)是一种编程范例,它提供了一种结构化程序的方法,以便将属性和行为捆绑到单个对象中。

有时,我们事先并不知道将传递给函数的参数数量.Python允许我们通过具有任意数量参数的函数调用来处理这种情况。

在函数定义中,我们在参数名称前使用星号(*)来表示这种参数。这是一个例子。

In [11]
def greet(*names):
   """This function greets all
   the person in the names tuple."""

   # names is a tuple with arguments
   for name in names:
       print("Hello",name)

greet("Monica","Luke","Steve","John")
('Hello', 'Monica')
('Hello', 'Luke')
('Hello', 'Steve')
('Hello', 'John')
在这里,我们使用多个参数调用该函数。这些参数在传递给函数之前被包装到元组中。在函数内部,我们使用for循环来检索所有参数。
虽然实例属性特定于每个对象,但类属性对于所有实例都是相同的 - 在这种情况下,属性都来自狗。

class Dog:

    # Class Attribute
    species = 'mammal'

    # Initializer / Instance Attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age

因此,虽然每只狗都有一个独特的名字和年龄,但每只狗都是哺乳动物。

让我们创造一些狗......
修改属性
您可以根据某些行为更改属性的值:

In [3]
class Email:
    def __init__(self):
        self.is_sent = False
    def send_email(self):
        self.is_sent = True
        
my_email = Email()
print(my_email.is_sent)

my_email.send_email()
print(my_email.is_sent)
False
True
在这里,我们添加了一种发送电子邮件的方法,该方法将is_sent变量更新为True。

实例就是个例,要实例化才能访问。类变量就是共有的,不实例化也能访问。无非就是变量和方法而已!

isinstance()函数用于确定实例是否也是某个父类的实例。

In [6]
# Parent class
class Dog:

    # Class attribute
    species = 'mammal'

    # Initializer / Instance attributes
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # instance method
    def description(self):
        return "{} is {} years old".format(self.name, self.age)

    # instance method
    def speak(self, sound):
        return "{} says {}".format(self.name, sound)


# Child class (inherits from Dog() class)
class RussellTerrier(Dog):
    def run(self, speed):
        return "{} runs {}".format(self.name, speed)


# Child class (inherits from Dog() class)
class Bulldog(Dog):
    def run(self, speed):
        return "{} runs {}".format(self.name, speed)


# Child classes inherit attributes and
# behaviors from the parent class
jim = Bulldog("Jim", 12)
print(jim.description())

# Child classes have specific attributes
# and behaviors as well
print(jim.run("slowly"))

# Is jim an instance of Dog()?
print(isinstance(jim, Dog))

# Is julie an instance of Dog()?
julie = Dog("Julie", 100)
print(isinstance(julie, Dog))

# Is johnny walker an instance of Bulldog()
johnnywalker = RussellTerrier("Johnny Walker", 4)
print(isinstance(johnnywalker, Bulldog))

# Is julie and instance of jim?
print(isinstance(julie, jim))
Jim is 12 years old
Jim runs slowly
True
True
False
覆盖父类的功能
请记住,子类也可以覆盖父类的属性和行为。举些例子:

In [7]
class Dog:
    species = 'mammal'

class SomeBreed(Dog):
    pass

class SomeOtherBreed(Dog):
     species = 'reptile'

frank = SomeBreed()
print(frank.species)

beans = SomeOtherBreed()
print(beans.species)
mammal
reptile
SomeBreed()类从父类继承物种,而SomeOtherBreed()类覆盖物种,将其设置为爬行动物~~~~~~~~