Python 如何创建该类对象的数组(列表或dict)?
参考: 有时,使用类似于Pascal“record”或C“struct”的数据类型,将几个命名的数据项捆绑在一起是很有用的。空的类定义可以很好地执行以下操作:Python 如何创建该类对象的数组(列表或dict)?,python,Python,参考: 有时,使用类似于Pascal“record”或C“struct”的数据类型,将几个命名的数据项捆绑在一起是很有用的。空的类定义可以很好地执行以下操作: class Employee: pass john = Employee() # Create an empty employee record # Fill the fields of the record john.name = 'John Doe' john.dept = 'computer lab' john.salar
class Employee:
pass
john = Employee() # Create an empty employee record
# Fill the fields of the record
john.name = 'John Doe'
john.dept = 'computer lab'
john.salary = 1000
我发现这种存储数据的方法非常有用,我是一个学习python的vb.Net的家伙,在vb中我会去的
Dim x(Mydata.getupperbound(0)) as Employee
and populate it like
For i as integer = 0 to Mydata.getupperbound(0)
x(i).name = mydata(i).Name
x(i).dept = mydata(i).dept
x(i).salary = mydata(i).salary
next
问:想在python中使用类似.Net结构的python类执行类似操作吗?如何做到这一点
感谢您在python中执行此操作的方法是创建一个具有所需属性的类
class Employee:
def __init__(self, name, dept, salary="100K"):
self.name = name
self.dept = dept
self.salary = salary
emp1 = Employee("Mark", "Sales", "150K")
emp2 = Employee("John", "Engineering") # Salary is set to default value of 100K
如果您想进行完整的数据抽象并将数据存储在一个对象中,那么请将类型列表中的名称、部门、薪资设置为,并使用sep函数将这些值添加到列表中
class Employee:
def __init__(self):
self.name = []
self.department = []
self.salary = []
def add_data(self, name, dept, salary):
self.name.append(name)
self.salary.append(salary)
self.department.append(dept)
names =['a', 'b', 'c']
depts =['x', 'y', 'z']
salary = [100,200,3000]
x = Employee()
for name, dept, sal in zip(names, depts, salary):
x.add_data(name, dept, sal)
for name, dept, sal in zip(x.name, x.department, x.salary):
print(name, dept, sal, sep='\t')
输出
a x 100
b y 200
c z 3000
如果我正确地阅读了问题标题,那么您拥有Employee类,在第一个列表中被实例化为john,并希望将其转换为dict或list?每个类都已经有一个
\uuuu dict\uuu
属性,您可以访问该属性:
>>> class Employee:
... pass
...
>>> john = Employee()
>>> john.name = 'John Doe'
>>> john.dept = 'computer lab'
>>> john.salary = 1000
>>>
>>> john.__dict__
{'name': 'John Doe', 'dept': 'computer lab', 'salary': 1000}
>>> john.__dict__['name']
'John Doe'
然后,您可以直接将john转化为dict:
>>> john = john.__dict__
>>> john['name']
'John Doe'
另请参见:如果您使用的是Python 3.7+,请完美地填充您的用例:
from dataclasses import dataclass
@dataclass
class Employee:
name: str
dept: str
# Could also be float if that fits better
# These are just annotations and do not actually control the held data type
salary: int
实例化它们很简单:
john = Employee('John Doe', 'computers', 1000)
bill = Employee('Billy Joe', 'marketing', 900)
dataclasses
模块还自动实现实例的漂亮打印:
>>>print(john)
Employee(name='John Doe', dept='computers', salary=1000)
>>>print(bill)
Employee(name='Billy Joe', dept='marketing', salary=900)
python中mydata的格式是什么?ie dict、csv等?@dataclass看起来很棒,谢谢,所以我可以用FOR或WHILE循环来填充它。谢谢