在python中初始化一个实例变量(例如self.my_var)时,你应该在你的类__init__函数中执行它,以便为每个实例的这个变量正确保留内存(< - 我的错误,见下文).如果要定义类级变量,可以在函数外部进行,而不使用self前缀.
当你比实例化一个函数内部变量等,会发生什么__init__用self前缀?它的行为就像一个普通的实例变量,有没有令人信服的理由不这样做?除了隐藏代码逻辑的危险之外,这已经足够了,但是我想知道如果你这样做,你可能会在内存或其他隐藏的问题上运行吗?
我无法找到在某处讨论的内容.
更新 抱歉
我误解了一些答案,包括第一个和第三个Python __init__和self他们做了什么?(寻找其他人)并认为这__init__是一种特殊类型的功能,认为它以某种方式具有内存分配功能(!?).错误的问题.
我只是想制作一个生成骰子的代码(在python中).这是代码:
import random
class Dice:
def _init_(self, number_dice):
self._dice = [6] * number_dice
def roll_dice(self):
for d in range(len(self._dice)):
self._dice[d] = random.randit(1, 6)
self._dice.sort()
def print_roll(self):
length = len(self._dice)
print(str(lenth) + "dice:" + str(self._dice))
my_dice = Dice(2)
my_dice.roll_dice()
my_dice.print_roll()
Run Code Online (Sandbox Code Playgroud)
编译器对第18行说了些什么.我是编程的新手,所以任何事情都有帮助=]
我想稍后使用张量流梯度来计算其他量。我需要在一个类中将目标函数和梯度作为函数进行数值计算(然后在其余套件中使用该类)。但是,以下代码出现错误:
import tensorflow as tf
class MyClass:
def __init__(self):
x=tf.Variable(tf.zeros(2))
func = tf.cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] + 0.2) * x[0]
diff_func = tf.gradients(func,x)
sess = tf.Session()
def getFunc(self,coords):
return self.sess.run(self.func,feed_dict={self.x:coords})
def getGrad(self,coords):
grad = self.sess.run(self.diff_func,feed_dict={self.x:coords})
return grad
MyClass = MyClass()
MyClass.getFunc([0.362,0.556])
MyClass.getGrad([0.362,0.556])
Run Code Online (Sandbox Code Playgroud)
我得到的错误是:
追溯(最近一次通话):
文件“”,第19行,位于MyClass.getFunc([0.362,0.556])中
getFunc中第11行的文件“”返回self.sess.run(self.func,feed_dict = {self.x:coords})
AttributeError:MyClass实例没有属性“ sess”
不确定如何使此类正常运行。谢谢。
可能重复:
Python init和self他们做了什么?
任何人都可以解释一下__init__(self)吗?我一直在读其他问题和人们提到超级课程?什么是超级课程?我认为程序应该从一开始
def print_word(word):
print word
Run Code Online (Sandbox Code Playgroud)
是__init__(self)某种特殊情况,因为它有下划线和"自我"吗?抱歉没有具体的术语......还在学习.
我想在类加载后将类注册到管理器,就像 http 处理程序注册到处理程序管理器一样。
可以通过其他方式完成,例如在映射中定义关系或在类定义后调用注册函数。
但是有没有更好的方法来自动执行此操作?
更新:
虽然沙丘的回答满足了我的需要。我正在努力改进这个问题,让它对遇到同样问题的其他人更有用。
以下是示例。
处理程序/__init__.py
handler/basehandler.py - classBase, HandlerManager
handler/handlerA.py - classA(classBase)
处理程序/处理程序B.py - classB(classBase)
handlerA 和 handlerB 包含 classA 和 classB,它们是 classBase 的子类。
classA 处理程序来自 /a/ 的请求,classB 处理程序 /b/
我需要在第一次导入处理程序模块时将它们自动注册到 HandlerManager。
class MyObject1(object):
def __init__(self):
super(MyObject1, self).__init__()
pass
class MyObject2(object):
def __init__(self, arg):
super(MyObject2, self).__init__()
pass
Run Code Online (Sandbox Code Playgroud)
我读过这样的python27代码,
我知道“超级”是指父类构造函数,
但我不明白为什么这两个类称自己为'构造函数' __init__',
好像没什么实际效果。
class test:
def __init__(self):
test_dict = {'1': 'one', '2': 'two'}
def test_function(self):
print self.test_dict
if __name__ == '__main__':
t = test()
print t.test_dict
Run Code Online (Sandbox Code Playgroud)
错误:
AttributeError: test instance has no attribute 'test_dict'
Run Code Online (Sandbox Code Playgroud)
此外,如果我执行代码:t.test_function()而不是print t.test_dict,也发生错误:
AttributeError: test instance has no attribute 'test_dict'
Run Code Online (Sandbox Code Playgroud)
为什么?我已经在函数中定义了test_dict __init__,所以它应该初始化为每个实例,但为什么python告诉我它找不到dict?
如果我使用__init__而不是init__在课堂上,有些东西不起作用.我很好奇这两者之间的区别是什么.
这是班级的一部分.但它确实无关紧要,因为它适用init__而且不适用__init__.我知道这是一个输入错误,然后它意味着我可以实际调用它.
class Point(namedtuple('Point', 'x, y, z')):
'class of a point as a tuple array'
__slots__ = () # prevent creation of instance dictionaries to save memory
def init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __del__(self):
'delete the Point'
def __repr__(self):
'Return a nicely formatted representation string'
return '[%r, %r, %r]' % (self)
def __str__(self):
'printing format'
return '%s[%r, %r, %r]' % (self.__class__.__name__, …Run Code Online (Sandbox Code Playgroud) 我在创建一个带有字符串的ctypes结构并用一个有意义的值初始化它时遇到了一些问题.
这是我的结构:
class MyStruct( Structure ):
_fields_ = [ ("someString", c_char_p) ]
Run Code Online (Sandbox Code Playgroud)
这是我试图初始化它
obj = MyStruct( "something" )
Run Code Online (Sandbox Code Playgroud)
两种尝试都失败了.这是错误消息:
obj_1 = MyStruct("something")TypeError:期望的字符串或整数地址而不是str实例
如果我使用*c_char_p*operator obj = MyStruct(c_char_p("something"))也会发生同样的事情
我必须提到这个代码是在Blender 2.63a环境中执行的.
任何人都可以帮我解决这个问题吗?
python ×9
class ×2
init ×2
ctypes ×1
dictionary ×1
inheritance ×1
methods ×1
self ×1
session ×1
string ×1
super ×1
tensorflow ×1
typeerror ×1