我无意中发现这种双重下划线名称的行为,但我不明白:
class A:
pass
class B:
pass
class C(A,B):
__id__ = 'c'
c = C()
print(C.__mro__) # print the method resolution order of class C
#print(c.__mro__) # AttributeError: 'C' object has no attribute '__mro__'
print(C.__id__) # print 'c&
在Python中,我可以使用@classmethod装饰器创建一个类方法:
>>> class C:
... @classmethod
... def f(cls):
... print(f'f called with cls={cls}')
...
>>> C.f()
f called with cls=<class '__main__.C'>
或者,我可以在元类上使用一个普通(实例)方法:
>>> class M(type):
... def f
尝试使用Python2的元类将单例更改为Python3,__new__返回:
[ ERROR ] Error in file Importing test library 'C:\Users\TestTabs.py' failed: __class__ not set defining 'BrowserDriver' as <class 'BrowserDriver.BrowserDriver'>. Was __classcell__ propagated to type.__new__?
代码:
class Singleton(ty
简单地说,Python描述了获取属性时的查找过程。这本书区分了两个案例
从类(例如cls.name )获取属性时的查找过程
从类获取属性
当您使用语法C.name来引用类对象C上的属性时,查找分两个步骤进行:
1. When `name` is a key in `C.__dict__`, `C.name` fetches the value `v` from `C.__dict__['name']` . Then, when `v` is a descriptor (i.e., `type(v)` suppl
我在一个文件中有一系列Python类。一些类引用另一些类。
我的代码是这样的:
class A():
pass
class B():
c = C()
class C():
pass
试着运行它,我得到了NameError: name 'C' is not defined。很公平,但是否有任何办法使它工作,或者我必须手动重新排序我的类来适应?在C++中,我可以创建一个类原型。Python有类似的吗?
(我实际上是在玩Django模型,但我尽量不让事情复杂化)。
我在玩python来理解它是如何工作的,但是有一些奇怪的东西。我在我的__new__中定义了一个MetaClass方法,我希望第四个参数(它是类的属性块)包含在我的类中定义的方法。
我有这样的代码:
#!/usr/bin/python3
class MyMetaClass(type):
def __new__(metacls, name, bases, attrs):
instance = super(MyMetaClass, metacls) #Create instance of super class, which metaclass is type
我试图理解Python中的“可调用性”是什么,类是可调用的意味着什么。我在玩以下代码:
class A(object):
def __init__(self):
pass
print("Is A callable? " + str(callable(A)))
a=A()
print("created a")
a()
这将产生以下结果:
Is A callable? True
created a
Traceback (most recent call last):
File "test2.py", line 11
我正在尝试构建一个包含Service实例的Registry类。Registry和Service类如下;
class Registry:
def __init__(self, registrar):
self.registrar = registrar
def get(self, key):
layers = key.split('.')
value = self.registrar
for item in layers:
value = value[item]
在Python语言中实现__len__(self)方法非常容易,这样它就可以像下面这样处理len(inst)调用:
class A(object):
def __len__(self):
return 7
a = A()
len(a) # gives us 7
您可以定义很多类似的方法(__eq__、__str__、__repr__等)。我知道Python类也是对象。
我的问题是:例如,我是否可以通过某种方式定义__len__,这样就可以实现以下功能:
len(A) # makes sense and gives some predictable result
我编写了一个包含嵌套元类的Python 3元类(与abc一起),如下所示:
class A_M(object, metaclass=abc.ABCMeta):
class A_nested_M(object, metaclass=abc.ABCMeta):
def ... # some methods
现在,实现如下
class A(A_M):
class A_nested(A_nested_M):
def ...
不起作用。那么,我是否错过了有关元类使用的一些内容,或者这种嵌套元类的实现根本不起作用?
#例如:
class example(object):
def someFunction():
print("I am some function")
def __init__(self,x,y):
self.x = x
self.y = y
someFunction()
为什么这段代码会产生没有定义someFunction的错误?是不是因为python的解释器在执行def someFunction代码之前执行def init代码块?我认为python的执行顺序是自上而下的方法。任何洞察力都将不
我想在python中实现单例模式,我喜欢中描述的模式。
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
class SingletonClass(metaclass=S
我目前正在编写DevExpress Report,我随处可见这种语法。我想知道它们是什么?它们是用来做什么的?我指的是方括号[]中的那个。在C#中我们叫它什么?
[XRDesigner("Rapattoni.ControlLibrary.SFEAmenitiesCtrlTableDesigner," + "Rapattoni.ControlLibrary")] // what is this?
public class SFEAmenitiesCtrl : XRTable
我正在创建一个元类,在其中我定制了__new__方法,以定制如何根据kwargs中提供的值创建新的类。在一个例子中,这可能更有意义:
class FooMeta(type):
def __new__(cls, name, bases, kwargs):
# do something with the kwargs...
# for example:
if 'foo' in kwargs:
kwargs.update({
'fooattr': '
我花了一些时间寻找如何决定如何在python类中存储数据和函数的指南。我应该指出,我是面向对象程序设计的新手,因此回答如下:
数据属性对应于Smalltalk中的“实例变量”,以及C++中的“数据成员”。(如中所示)
让我挠我的头。我想我想要的是面向python程序员的OOP入门。我希望指南/入门手册也包含某种术语表或定义,因此在阅读完之后,我将能够明智地谈论不同类型的可用变量。我想了解在下面的代码中决定何时使用a、b、c和d形式的思想过程。
class MyClass(object):
a = 0
def __init__(self):
b = 0
这有点难以解释,但这是我想要做的:我想在我的类上创建一个函数/属性,它将执行以下操作。无论我访问哪个字段,它都会将该字段的值与其他属性进行比较,并返回一些内容。
例如:
class myClass(object):
a = 1
b = 2
c = 3
def myProp(sef, accessed_attribute):
return someting like you accessed <name of attrib> and it is the largest value of all all of the attribue
在下面的类型记录代码中,我想调用一个需要导入的函数。我可以在类的构造函数中初始化导入,但是如何在公共函数中实现呢?
import {Http} from "angular2/http";
export class AppComponent {
constructor( properties.
public http: Http
) {
this.http.get(...){} //FUNCTION 1: this function works fine
this.getAll(); //this does not work as
运行以下代码:
class NonMeta:
def __new__(cls):
x = super().__new__(cls)
x.attr = 100
return x
class Meta(type):
def __new__(mcs, name, bases, dct):
x = super().__new__(mcs, name, bases, dct)
x.attr = 100
return x
class WithMeta(metaclass=Meta):