我有一个主player类,它由两个子类bot1和bot2继承。在player类中,我希望有一个变量来跟踪bot子类上次采取的操作。
class player:
def printstuff(self):
print self.lastplay.name(self)
def __init__(self, name):
self._name = name
self.lastplay = 0
main
p1 = player.StupidBot("sb") #both of these modify lastplay
我试图访问外部函数中的类变量,但是我得到了AttributeError,“类没有属性”--我的代码如下所示:
class example():
def __init__():
self.somevariable = raw_input("Input something: ")
def notaclass():
print example.somevariable
AttributeError: class example has no attribute 'somevariable'
其他的问题也被问到了类似的问题,然而
>>> class Foo:
... 'it is a example'
... print 'i am here'
...
i am here
>>> Foo.__name__
'Foo'
>>> Foo().__name__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: Foo instance has no
我试着理解Python中的元类黑魔法。例如,可以使用AFAIK、元类来确保在派生类中实现某些方法,但我有一个问题,即子类。似乎我需要显式地实现所有必需的派生方法,即使没有理由(?)做那件事。
看看这个:
~ $ ipython
Python 3.6.5 (default, Apr 14 2018, 13:17:30)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.3.1 -- An enhanced Interactive Python. Type
关于运行以下代码的行为,我有两个问题。为什么在没有实例化对象的情况下调用__new__?我认为__new__控制了一个新实例的创建。接下来,为什么当AttributeError返回True的大小时,hasattr会引发
class ShapeBase(type):
def __new__(cls, name, bases, attrs):
rv = super(ShapeBase, cls).__new__(cls, name, bases, attrs)
parents = [base for base in bases if isinstance(base, Shap
问题
使用mock.patch和autospec=True对类进行修补并不能保留该类实例的属性。
The Details
我正在尝试测试一个类Bar,它将类Foo的实例实例化为名为foo的Bar对象属性。正在测试的Bar方法称为bar;它调用属于Bar的Foo实例的方法foo。在测试时,我是在模仿Foo,因为我只想测试Bar是否访问了正确的Foo成员:
import unittest
from mock import patch
class Foo(object):
def __init__(self):
self.foo = 'foo'
class
我想在matlab中调用tensorflow的python (参见)。matlab不支持"with“语句。如果没有"with“语句,我就无法创建tf.variable_scope。我试过以下两种密码,但两者都不起作用。有什么解决办法吗?
Python:
import tensorflow as tf
with tf.variable_scope('123') as vs:
print(vs.name) # OK
vs2 = tf.variable_scope('456')
print(vs2.name) # AttributeErro
我编写了一个小类来尝试使用自定义的__getattr__方法,每次运行它,我都会得到一个属性错误:
class test:
def __init__(self):
self.attrs ={'attr':'hello'}
def __getattr__(self, name):
if name in self.attrs:
return self.attrs[name]
else:
raise AttributeError
t = test()
pr
似乎Python处理AttributeError异常是不标准的。当类定义__getattr__方法时,它会吞并此异常,而不是传播到堆栈顶部。原来的异常丢失了吗?
class A(object):
@property
def test(self):
raise AttributeError('message which should not be lost')
return 'this would never return'
def __getattr__(self, name):
prin
我有以下课程:
class A:
def name(self):
return self.__label
class B(A):
def __init__(self, name)
self.__label = name
ex1 = B('Tom')
print ex1.name()
我得到的是:
AttributeError: B instance has no attribute '_A__label'
有什么问题,怎么纠正?
在python work下一段代码中:
class MyClass(object):
field = 1
>>> MyClass.field
1
>>> MyClass().field
1
当我想要自定义字段的返回值时,我使用下面的代码:
class MyClass(object):
def __getattr__(self, name):
if name.startswith('fake'):
return name
raise AttributeError("%
我有以下几种型号:
class A(Model):
pass
class B(Model):
a = ForeignKey(A, related_name = 'b')
b_field = CharField(max_length=64)
现在我想序列化一个A对象,其中我希望有第一个b对象。我以前有这样的代码:
class BSerializer(ModelSerializer):
class Meta:
model = B
fields = '__all__'
class ASerializ
在Python中,我可以定义:
class Person(object):
name = "Easwar"
age = 35
sex = "male"
class Occupation:
name = "my_job"
然后我就可以访问它了
>> p = Person()
>> p.Occupation.name
>> # prints "my_job"
然而,在Django中,如果我有一个定义了类Meta的模型,我就不能这样做
>>> m
我是Python的新手,我遇到了一个问题:在我使用的包中,有一个命令,我可以用以下方式回忆起来: example.D1,example.D2,改变了D后面的数字,我想创建一个循环,用来打印所有结果,后面是D,从1到100。
我试过了
for i in range(1, 100):
print(example.Di)
错误是raise AttributeError("'*' has no attribute '%s'" % name) AttributeError: '*' has no attribute 'Di&
Class MyClasse:
nom="me"
age=24
def __delattr__(self,name)
if name=="nom":
raise AttributeError( "you are not allowed")
else:object.__delattr__(self,name)
A=MyClasse()
del A.age
class Person:
def __init__(self, name):
self.name = name
# Getter function
@property
def name(self):
return self._name
# Setter function
@name.setter
def name(self, value):
if not isinstance(value, str):
raise TypeError('Expe
Django文档说:
class CommonInfo(models.Model):
...
class Meta:
abstract = True
ordering = ['name']
class Student(CommonInfo):
...
class Meta(CommonInfo.Meta):
db_table = 'student_info'
但是如果CommonInfo和学生在不同的文件中,我该如何处理呢?目前,我的学生文件看起来像这样
from CommonIn
给予:
In [37]: class A:
....: f = 1
....:
In [38]: class B(A):
....: pass
....:
In [39]: getattr(B, 'f')
Out[39]: 1
好吧,要么叫超级还是爬mro?
In [40]: getattr(A, 'f')
Out[40]: 1
这是意料之中的。
In [41]: object.__getattribute__(A, 'f')
Out[41]: 1
In [42]: object.__getattri
主要是为了好玩,为了帮助我正在编写的解析器中的一些人机工程学,我非常想重写一个类的__getattr__,而不是对它的子类做同样的事情。为了解释这一点,下面是一些代码:
class AttrMeta(type):
def __getattr__(self, name):
if name == "A":
return "hi there."
class Main(metaclass=AttrMeta):
pass
class Subclass(Main):
pass
print(Main.A)
我有一个类,其中我使用描述符来防止对其某些属性的更改。
class Frozen:
"""cannot change attribute if it already exists"""
def __set_name__(self, owner, name):
self.storage_name = name
def __set__(self, instance, value):
if self.storage_name in instance.__dict__:
背景 我希望使用元类,以便在原始类的基础上添加帮助器方法。如果我希望添加的方法使用self.__attributeName我得到一个AttributeError (由于名称混乱),但对于现有的相同方法,这不是问题。 代码示例 下面是一个简化的例子 # Function to be added as a method of Test
def newfunction2(self):
"""Function identical to newfunction"""
print self.mouse
print self._dog