自定义Python类
__init__
函数无法正确生成变量或调用函数。
我有以下代码,我希望用它来存储和操作有关网格面的信息。我遇到了
__init__
函数似乎没有执行任何操作的问题。
class Face():
"""A class to store and manipulate information about a face"""
def __int__(self):
self.face_id = 0
self.vertices=[0,1,2]
self.color=[255,255,255]
self.bright=False
self.transparency=0
self.light_sprite=False
self.normal_location=[0,0,0]
self.normal_vector=[0,0,0]
self.double_sided=False
print(self.light_sprite)
def set_srf_normal(self, data):
"""Set the normal information of the face from a SRF format"""
self.normal_location = [float(i) for i in data[:3]]
self.normal_vector = [float(i) for i in data[3:]]
# Determine if face is double-sided if the normal vector is zero for all elements.
double_sided = True
for i in self.normal_vector:
if i != 0:
double_sided = False
break
self.double_sided = double_sided
def set_srf_color(self, data):
"""Set the face color from a SRF format input"""
self.color = [int(i) for i in data]
# Valid colors component values are 0-255.
for idx, color in enumerate(self.color):
if color > 255:
self.color[idx] = 255
elif color < 0:
self.color[idx] = 0
def print_properties(self):
print(self.face_id, self.vertices, self.color, self.normal_location, self.normal_vector,
self.color, self.light_sprite, self.transparency, self.bright, self.double_sided)
face = Face()
print(face.face_id)
当我运行此代码时,我期望有 2 个打印输出。一首来自
print(self.light_sprite)
中的 __init__
,一首来自最后一行 print(face.face_id)
。
>>> False
>>> 0
但是我收到以下错误:
Traceback (most recent call last):
File "/Users/Documents/testing.py", line 46, in <module>
print(face.face_id)
AttributeError: 'Face' object has no attribute 'face_id'
现在,当我用这些行替换最后两行时,突然face.face_id存在并且可以打印。
face = Face()
face.face_id = 0
print(face.face_id)
>>> 0
如果我调用其中一个类函数,由函数更新的类变量现在突然存在。
face = Face()
print(face.color)
Traceback (most recent call last):
File "/Users/Documents/testing.py", line 46, in <module>
print(face.color)
AttributeError: 'Face' object has no attribute 'color'
face = Face()
face.set_srf_color([0,255,0])
print(face.color)
print(face.face_id)
>>> [0, 255, 0]
>>> Traceback (most recent call last):
File "/Users/Documents/testing.py", line 48, in <module>
print(face.face_id)
AttributeError: 'Face' object has no attribute 'face_id'
我觉得我缺少一些基本的东西,但我看不到它。我将不胜感激任何可以帮助我理清原因的人:
__init__
函数未运行并调用打印命令__init__
函数未初始化类实例中的变量您的课程有一个拼写错误。您在第三行写的是
__int__
而不是 __init__
。
__int__
是一个单独的内置方法,用于将类本身转换为整数类型。
例如:
class Face:
# some init method
def __init__(self, value):
self.value = value
def __int__(self):
return int(self.value) + 1
f = Face("1")
print(int(f) + 1)
将打印出来
3