Untitled

 avatar
unknown
plain_text
3 years ago
2.0 kB
2
Indexable
# Session 1 : class objects -- initializing instances.

#Creating an empty class named "Employee"
class Employee:
	#Define a class attribute ("Global attribute" within the class.)
	#Class attributes won't check anything for you.
	# If you define a checking on __init__, it only works for that part. 
	# So if you want your method() or attributes can interact with it,
	# You need to specify the checking on every part involved it. 
	MIN_salary = 30000 #<--- no self

	def min_salary_check(_salary_input):
		if _salary_input >= Employee.MIN_salary:
			final_salary = salary_inputalary
		else:
			final_salary = Employee.MIN_salary
		return final_salary

	#(Not necessary but most class object has this: init constructor)
	def __init__(self, name="Not specified yet", salary=0):
		#Create the name and salary attributes
		#Listing all attributes here and also links them with the inputs. 
		self.name = name
		self.salary = min_salary_check(salary)
		
		#Creating conditionings for attributes if applicable
		#if salary >= Employee.MIN_salary:
		#	self.salary = salary
		#else:
		#	self.salary = Employee.MIN_salary
    
	#Alternative constructor: classmethod
	#Because one class can only have one __init__, so we need class method to 
	# introduce extra ways to initialize instance
	@classmethod
	def from_file(cls,filename):
			with open(filename,"r")as f:
				name = f.readline()
			return cls(name)
	
	#Alternative constructor
	def from_str2(self,datestr):
		#cls refers to "class", will call __init__().
		parts = datestr.split("-")
		year, month, day = int(parts[0]), parts[1], parts[2]
		# Return the class instance
		return  int(year), int(month),int(day)

	
	def set_name(self, new_name):
		self.name=new_name
	
	def set_salary(self,new_salary):
		self.salary=new_salary

#Created an object emp of class Employee
emp = Employee()

#Setting up attributes for your class object
#emp = Employee('Eric',5000)
emp.set_name("Eric")
emp.set_salary(5000)

print(emp.salary)