我试图在用cls.dates修饰的类中定义的两个方法中访问@classmethod,但是下面的代码给出了一个错误Database has no attribute dates。我需要帮助才能在方法上访问它。
class Database:
""" class that works with data storage and retrieval. """
def __init__(cls, file='D:\\vscode\\Python\\data.db'):
# initialise database
我读过
我试着从这个例子中复制上元类,发现这并不是在所有情况下都有效的:
def upper(cls_name, cls_parents, cls_attr):
""" Make all class attributes uppper case """
attrs = ((name, value) for name, value in cls_attr.items()
我有一个类,它有一个类变量和一个静态方法,我需要让类变量包含一个对静态方法的回调。
这门课看上去像:
class Test(object):
ref = ???? #this should be my reference
@staticmethod
def testmethod(anyparam="bla"):
print "it works"
我该怎么做?这有可能吗?
我正在使用python 2
编辑:真正的例子是:
class reg(cmd):
bla = {
'def'
我有一个类装饰器,它应该添加一个__init_subclass__方法,但当我这样做时: class A:
def __init_subclass__(cls, **kwargs):
print(cls)
class B:
pass
def p(cls, **kwargs):
print(cls)
B.__init_subclass__ = p
class C(A):
pass
# Prints class C
class D(B):
pass
# TypeError: p() missing 1 required positional argument:
我正在为一些python模块编写单元测试。但是,我想不出一种方法来模拟导入实例的方法。下面是我想要测试的python模块。
--bar.py--
class A():
@classmethod
def method_1(self):
...
a = A()
--foo.py--
from bar import a
class B():
@classmethod
def b(cls):
if a.method_1():
return True
else:
ret
我想我理解python中“名称损坏”的概念,但我可能错过了一些东西。看看下面的代码:
#!/usr/bin/env python
class Base(object):
__data = "Base"
@classmethod
def func(cls):
return "Class name is {}, data is {}".format(cls.__name__, cls.__data)
class A(Base):
__data = "A"
class B(A):
__
我在网上看到了一些关于如何利用python元类将类强制创建为Singleton的资料。代码片段大致如下:
class SingletonMetaClass(type):
_instance = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instance:
# usually a lock is used here, but omitted for simplicity
cls._instance[cls] = super().__call_
尝试使用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
我有一段代码如下
object TestReflection {
def main(args: Array[String]): Unit = {
val cls = Class.forName("test.Child")
cls.getDeclaredField("w")
cls.getDeclaredField("x")
cls.getDeclaredField("z")
}
}
class Parent(val x : Int, val t : Int) {
}
class Chil
我想在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
我有以下代码(python 3):
import inspect
def get_class_for_method(method):
if inspect.ismethod(method):
for cls in inspect.getmro(method.__self__.__class__):
if cls.__dict__.get(method.__name__) is method:
return cls
method = method.__func__ # fallback to _