Python 对象表现得像函数

Python 对象表现得像函数

flyfish

面向对象编程里有句话一切皆对象。everything is an object,python里就是这样

module 是 object

import math
my_math = math
my_math.a=1 #为module object新增一个名为a的属性
print(my_math.a)

class 是 object

class Person:

    unknown_age = "unknown_age"

    def __init__(self, name, age=None):
        self.name = name
        self.age = age
        print("__init__ call")

    def show_age(self):
        if self.age is None:
            print("show_age:unknown_age")
            return self.unknown_age
        print("show_age:",self.age)
        return self.age

#通常的写法
xiaoming = Person("xiaoming")
xiaoming.show_age()

# class 是 object
my_class = Person
xiaoming = my_class("xiaoming",10)
xiaoming.show_age()

结果

# __init__ call
# show_age:unknown_age
# __init__ call
# show_age: 10

class是 object
instance of classes是object
module 是object
function 是object
也就是
everything is an object.

对象表现得像函数

在python里函数是first-class object 一等对象
first-class object 与first-class citizen(一等公民), first-class value 同样的意思
根据
一等荣誉学位(First Class Honours
二等一级荣誉学位(Upper Second Class Honours) 及格线在此
三等荣誉学位(Third Class Honours)

first-class object 是好的,是个褒义词,second-class object就是次好的。

按照wiki的解释
An object is first-class when it:

can be stored in variables and data structures
can be passed as a parameter to a subroutine
can be returned as the result of a subroutine
can be constructed at runtime
has intrinsic identity (independent of any given name)

Depending on the language, this can imply:

being expressible as an anonymous literal value
being storable in variables
being storable in data structures
having an intrinsic identity (independent of any given name)
being comparable for equality with other entities
being passable as a parameter to a procedure/function
being returnable as the result of a procedure/function
being constructible at runtime
being printable
being readable
being transmissible among distributed processes
being storable outside running processes

对象表现得像函数,只需要实现实例方法__call__

也就是在类型定义了__call__方法,那么它的实例可以作为函数调用。

可以对比下 对象.方法 的方式调用

class Person:
 
    def __init__(self, age):
        self.age = age
 

    def now_age(self,age):
        self.age = age
        print("now age:", self.age)
 
p = Person('10')
p.now_age(11)

像函数那样调用

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print(self.name)
        print(self.age)

    def __call__(self, age):
        self.age = age
        print("now age:", self.age)
     
p = Person('xiaoming', '10')
p('11') 

输出

xiaoming
10
now age: 11

你可能感兴趣的:(#,Python,python)