OOP的概念在Python的

时间:2017-02-13 11:37:31

标签: python-2.7 function parameters

这是代码的主要文件:

formControlName must be used with a parent formGroup directive.  You'll want to add a formGroup

la_class文件:

#for student registration in a college
from la_class import *
from la_class0 import *
from la_class1 import *

student1_name = Student(name1)
student1_pref = Branch(pref)

print("Student1 details : ",student1_name.name)
print("Student1 branch : ",student1_pref.preference )

student1_course = Course(core,el1,el2)

print("core course---",student1_course.core)
print("elective course---1.",student1_course.elective1)
print("elective course---2.",student1_course.elective2)

la_class0 file:

 #takes the student name input
 class Student:
  def __init__(self,name):
   self.name = name

 print("___student details___ ")
 name1 = raw_input("name1 > ")

la_class1文件:

 #this contains the preference operations 
 class Branch:
  def __init__(self,pref):
  self.preference = pref
 print("__________")
 print("(1.) __CSE__")
 print("(2.) __CCE__")
 print("(3.) __ECE__")
 print("(4.) __MME__")

 usr = raw_input("_choose the above preferences_ ")

 if usr is "1":
  pref = "CSE"
 elif usr is "2":
  pref = "CCE"
 elif usr is "3":
  pref = "ECE"
 else:
  pref = "MME"          

此处代码仅适用于一个学生对象,即 student1 ,如何实现代码,以便用户可以按照自己的意愿获得尽可能多的学生注册(应该是面向对象的)? / p>

2 个答案:

答案 0 :(得分:0)

您可以使用:

class Student:
  def __init__(self, *args, **kwargs):
    # args is a list, positional
    # kwargs is a dict
    self.names = args
    self.first_name = args[0]

student = Student ("john", "doe")

答案 1 :(得分:0)

Python是动态类型的,这意味着每个变量都可以存储整数,字符串,列表,元组,函数,对象,类等。

所以你可以简单地构建一个列表:

names = ["tom","alice","bob"]
preferences = ["cse","math","lang"]

并且例如将其提供给构造函数:

student0 = Student(names[0],prefs[0]) #student Tom likes cse
student1 = Student(names[1],prefs[1]) #student Alice likes math
student2 = Student(names[2],prefs[2]) #student Bob likes lang

因为names[0]将访问names的第0个元素。

您甚至可以使用zip列表理解轻松构建学生列表:

students = [Student(name,pref) for name,pref in zip(names,preferences)]

相当于:

# equivalent to
students = [Student("tom","cse"),Student("alice","math"),Student("bob","lang")]