首先来看一个函数间的调用
类方法:
执行结果:
metaclass能有什么用处,先来个感性的认识:
①1 在wiki上面,metaclass是这样定义的:In object-oriented programming,
a metaclass is a class whose instances are classes.
Just as an ordinary class defines the behavior of certain objects,
a metaclass defines the behavior of certain classes and their instances.
也就是说metaclass的实例化结果是类,而class实例化的结果是instance.我是这么理解的:
metaclass是类似创建类的模板,所有的类都是通过他来create的(调用 new ),这使得你可以自由的控制
创建类的那个过程,实现你所需要的功能.
当然你也可以用函数的方式(下文会讲)
name: 类的名字
bases: 基类,通常是tuple类型
attrs: dict类型,就是类的属性或者函数
metaclass的原理其实是这样的:当定义好类之后,创建类的时候其实是调用了type的 new 方法为这个类分配内存空间,创建
好了之后再调用type的 init 方法初始化(做一些赋值等).所以metaclass的所有magic其实就在于这个 new 方法里面了.
说说这个方法: new (cls, name, bases, attrs)
cls: 将要创建的类,类似与self,但是self指向的是instance,而这里cls指向的是class
name: 类的名字,也就是我们通常用类名. name 获取的.
bases: 基类
attrs: 属性的dict.dict的内容可以是变量(类属性),也可以是函数(类方法).
所以在创建类的过程,我们可以在这个函数里面修改name,bases,attrs的值来自由的达到我们的功能.这里常用的配合方法是
getattr和setattr(just an advice)
下面实现python中在一个类中调用另一个类的函数方法
或者下面来一个号理解的例子
先来介绍内部类与外部类是什么?
看源码解析:
内部类调用外部类的类属性和类方法
参考文献1
内置函数可以直接使用啊,比如使用内置函数查看一个对象的类型,type(obj),例如:
name?=?"zhangsan"
print(type(name))
#?输出
type?'str'
python的常用内置函数
①abs() 函数返回数字的绝对值
dict()
{} ? ? ?#创建一个空字典类似于u={},字典的存取方式一般为key-value
help('math')查看math模块的用处
help(a)查看列表list帮助信息
dir(help)
['__call__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']
a
①.0
next(it)
id(a)
a=["tom","marry","leblan"]
list(enumerate(a))
oct(10)
①.0. bin() 返回一个整数 int 或者长整数 long int 的二进制表示
bin(10)
'0b1010'
'0b1111'
①.1.eval() 函数用来执行一个字符串表达式,并返回表达式的值
f=open('test.txt')
bool()
False
bool(1)
True
bool(10)
bool(10.0)
isinstance(a,int)
isinstance(a,str)
class ? User(object):
? ? def__init__(self):
class Persons(User):
? ? ? ? ? super(Persons,self).__init__()
float(1)
①0
float(10)
①.0.0
iter(a)
for i in iter(a):
... ? ? ? ? print(i)
...
tuple(a)
s = "playbasketball"
len(s)
len(a)
class User(object):
? ?def __init__(self,name):
? ? ? ? ? ? self.name = name
? def get_name(self):
? ? ? ? ? ? return self.get_name
? @property
? ?def name(self):
? ? ? ? ? ?return self_name
list(b)
range(10)
range(0, 10)
class w(object):
a = w()
getattr(a,'s')
complex(1)
(1+0j)
complex("1")
max(b)
class Num(object):
...? ? a=1
.. print1 = Num()
print('a=',print1.a)
a= 1
print('b=',print1.b)
print('c=',print1.c)
delattr(Num,'b')
Traceback (most recent call last):? File "", line 1, inAttributeError: 'Num' object has no attribute 'b'
hash("tom")
a= set("tom")
b = set("marrt")
a,b
({'t', 'm', 'o'}, {'m', 't', 'a', 'r'})
ab#交集
{'t', 'm'}
a|b#并集
{'t', 'm', 'r', 'o', 'a'}
a-b#差集
{'o'}
以上就是土嘎嘎小编为大家整理的python内部函数调用相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!