def __init__(self, name, salary, age, subunit):
self.name = name
self.salary = salary
self.age = age
self.subunit = subunit
print("Employee is created! ")
def getdetails():
print(f"The name of the employee is {self.name}“)
print(f"The Salary of the employee is {self.salary}”)
print(f"The age of the employee is {self.age}“)
print(f"The subunit of the employee is {self.subunit}”)
jack = Employee(“Jack”, 100, 35, “Vs Code”)
jack.getdetails()
from dataclasses import dataclass, field
@dataclass
class Employee:
name: str
salary: int
age: int
subunit: str
company: str = field(default="Microsoft")
def getdetails(self):
print(f"name, {self.name}")
jack = Employee("Jack", 100, 35, "Vs Code")
jack.getdetails()
for further reducing repetition,
we could refactor the getdetails method
def getdetails(self):
a = ['name', 'salary', 'age', 'subunit']
print('\n'.join(f"The {i} of the employee is {j}" for i, j in zip(a, [getattr(self, i) for i in a])))
or even,
def getdetails(self):
print('\n'.join(f"The {i} of the employee is {j}" for i, j in zip((a := ['name', 'salary', 'age', 'subunit']), [getattr(self, i) for i in a])))
or,
getdetails = lambda self: print('\n'.join(f"The {i} of the employee is {j}" for i, j in zip((a := ['name', 'salary', 'age', 'subunit']), [getattr(self, i) for i in a])))
Any function that is trying to access self.<thing> needs to be a method. To be a method, it needs to accept self as a parameter, and be defined inside the class. (Technically it doesn’t HAVE to be defined inside the class, but it’s easier to, especially since you’re just starting out.)
By the way, when posting code here, it’s usually best to use an explicit code block, to make sure your formatting doesn’t get messed up. Otherwise it’s sometimes tricky to figure out which parts are inside what.