class A:
def foo(self):
print "foo()"
getattr(A, foo) # True
A.foo() # error
getattr(A(), foo) # True
A().foo() # prints "foo()"
Run Code Online (Sandbox Code Playgroud)
话虽这么说,这是我的问题:
我希望将测试用例元信息存储为测试用例类对象本身的属性,而不是存储在它们的实例上。
我有一个要提取的属性名称列表,但如果存在同名的实例方法,则将getattr(class_obj, attr)返回 True,但getattr(class_obj, attr)()会引发错误。
有没有办法告诉 getattr 不包含实例化类的属性而仅包含类对象本身的属性?
编辑:我尝试class_obj.__dict__直接访问(我理解这是不好的做法),但它不包含一些属性,例如__name__
编辑:改写问题。有没有办法区分 obj 类的方法和类实例的方法?
有时,一个类会有其他方法调用的“私有” : @classmethod
class FooClassThisSometimesHasALongNameEspIfAUnittestSubclasss(...):
@classmethod
def foo():
...
def bar(self):
...
FooClassThisSometimesHasALongNameEspIfAUnittestSubclasss.foo()
...
Run Code Online (Sandbox Code Playgroud)
可以看到,类名是重复的;诚然,这可能还没有严重到导致当前技术崩溃并引发僵尸大灾难,但它仍然是一种DRY违规,而且有点烦人。
类似问题super的答案表明这是Py3 新的原因之一super。
在缺少某些神奇normal()函数(与 相反super(),返回当前类)的情况下,是否有某种方法可以避免重复?
我有一个名为 my_module 的 python 模块,在其中我有一个名为 my_class 的类,而 my_class 有一个名为 my_method 的类方法。
基于我在周围看到的其他示例,我提出了以下从 C++ 调用 my_method 的尝试,但目前所有这些尝试都返回 NULL(实际上是其中一个段错误......)
首先我导入模块和类:
PyObject* my_module_name = PyString_FromString((char*)"my_module");
PyObject* myModule = PyImport_Import(my_module_name);
PyObject* my_class = PyObject_GetAttrString(myModule2, (char*)"my_class");
if (!my_class) std::cout << "my_class failed " << std::endl;
Run Code Online (Sandbox Code Playgroud)
然后我构建用于作为元组传入的参数:
// These are the args
PyObject* my_args = PyTuple_Pack(
5,
PyString_FromString((char*)"first string"),
PyString_FromString((char*)"next string"),
PyFloat_FromDouble(0.0),
PyFloat_FromDouble(1.0),
Py_False
);
if (!my_args) std::cout << "my_args failed " << std::endl;
Run Code Online (Sandbox Code Playgroud)
然后我尝试调用实际方法
PyObject* my_method = PyObject_GetAttrString(my_class,(char*)"my_method");
if (!my_method) std::cout << "failed " << …Run Code Online (Sandbox Code Playgroud) class Hello:
def load(self):
self.open('World')
@classmethod
def open(cls,print_string):
print 'Hello ' + print_string
class Hello:
def load(self):
Hello.open('World')
@classmethod
def open(cls,print_string):
print 'Hello ' + print_string
Run Code Online (Sandbox Code Playgroud)
我发现很难理解上面两个类调用类方法的不同风格。一个人在调用时使用 self 和另一个类名,什么时候应该使用第一个,什么时候应该使用第二个?
好的解释会真正澄清@classmethod概念。
我有一个包含所有 AWS 区域的 Python 类。我编写了一个类方法,它将返回所有区域的列表。有没有更好的方法来返回所有类变量值,这样我就不必像下面的示例中那样对 return 语句中的所有值进行硬编码?
class AwsRegion():
'''
Class to define AWS Regions
'''
OHIO = 'us-east-2'
NORTH_VIRGINIA = 'us-east-1'
NORTH_CALIFORNIA = 'us-west-1'
OREGON = 'us-west-2'
MUMBAI = 'ap-south-1'
SEOUL = 'ap-northeast-2'
SINGAPORE = 'ap-southeast-1'
SYDNEY = 'ap-southeast-2'
TOKYO = 'ap-northeast-1'
FRANKFURT = 'eu-central-1'
IRELAND = 'eu-west-1'
LONDON = 'eu-west-2'
SAO_PAULO = 'sa-east-1'
@classmethod
def all(cls, ):
return [AwsRegion.OHIO, AwsRegion.NORTH_VIRGINIA, AwsRegion.NORTH_CALIFORNIA, AwsRegion.OREGON, \
AwsRegion.MUMBAI, AwsRegion.SEOUL, AwsRegion.SINGAPORE, AwsRegion.SYDNEY, AwsRegion.TOKYO, \
AwsRegion.FRANKFURT, AwsRegion.IRELAND, AwsRegion.LONDON, AwsRegion.SAO_PAULO]
Run Code Online (Sandbox Code Playgroud) 我有一个类,它包含一些成员x(例如,所有实例都需要但独立于它们的一些数据):
class Foo(object):
x = 23
# some more code goes here
Run Code Online (Sandbox Code Playgroud)
现在,确定的过程x变得更加复杂,而且我希望能够x在某些时间“刷新”,所以我决定为其编写一个额外的函数
class Foo(object):
@classmethod
def generate_x(cls):
cls.x = 23
# some more code goes here
Run Code Online (Sandbox Code Playgroud)
但是,该类定义缺少 的初始化调用generate_x。
到目前为止我尝试过的:
这不起作用:
class Foo(object):
# generate_x() # NameError: name 'generate_x' is not defined
# Foo.generate_x() # NameError: name 'Foo' is not defined
@classmethod
def generate_x(cls):
cls.x = 23
Run Code Online (Sandbox Code Playgroud)
这可行,但不太清楚,因为代码是在类定义之外使用的
class Foo(object):
@classmethod
def generate_x(cls):
cls.x = 23
# ...
Foo.generate_x()
Run Code Online (Sandbox Code Playgroud)
有更好的替代方案吗?这里使用的是@classmethod最好的方法吗?我正在搜索的是 …
我想使用 Python3 partialmethod并且我无法调用结果函数。我的代码基于 Python 文档https://docs.python.org/release/3.6.4/library/functools.html 中的示例
from functools import partialmethod
class AClass():
def __init__(self):
self.v = val
def _fun(self, x):
z = x + self.v # some computation
return z
def fun(self, x):
return partialmethod(self._fun, x)
a = AClass(10)
b = a.fun(1)
print(b()) # TypeError: 'partialmethod' object is not callable
print(a.b()) # AttributeError: 'AClass' object has no attribute 'b'
Run Code Online (Sandbox Code Playgroud)
我明白为什么a.b()不正确,因为 b 没有在实例化的 a 中定义。的错误消息b()没有给我足够的信息来了解发生了什么。
如何定义带有绑定参数的方法并从封闭类外部调用它?这是可能的,还是有更好的方法来实现这个结果?
我有这个代码:
from typing import Callable, Any
class Test(classmethod):
def __init__(self, f: Callable[..., Any]):
super().__init__(f)
def __get__(self,*args,**kwargs):
print(args) # why out put is (None, <class '__main__.A'>) where form none why no parameter 123
# where was it called
return super().__get__(*args,**kwargs)
class A:
@Test
def b(cls,v_b):
print(cls,v_b)
A.b(123)
Run Code Online (Sandbox Code Playgroud)
为什么输出是(None, <class '__main__.A'>)?它是从哪里来的?None为什么它不是我调用它的参数 123 ?
请参阅下面的 Python 3.10 代码片段:
import contextlib
class Foo:
@contextlib.contextmanager
@classmethod
def state(cls):
try:
yield
finally:
pass
with Foo.state():
pass
Run Code Online (Sandbox Code Playgroud)
它抛出一个TypeError:
Traceback (most recent call last):
File "/path/to/code/play/quick_play.py", line 12, in <module>
with Foo.state():
File "/path/to/.pyenv/versions/3.10.5/lib/python3.10/contextlib.py", line 281, in helper
return _GeneratorContextManager(func, args, kwds)
File "/path/to/.pyenv/versions/3.10.5/lib/python3.10/contextlib.py", line 103, in __init__
self.gen = func(*args, **kwds)
TypeError: 'classmethod' object is not callable
Run Code Online (Sandbox Code Playgroud)
可以用classmethod来装饰吗contextlib.contextmanager?如果是的话,该怎么做?
我需要能够确定是否调用了类方法.我怎么能用OCMock做到这一点?
class-method ×10
python ×8
c++ ×1
class ×1
dry ×1
evaluation ×1
getattr ×1
mocking ×1
objective-c ×1
ocmock ×1
oop ×1
python-3.x ×1
python-c-api ×1
unit-testing ×1