0

I am new in python and have a simple question… In my project there is an "student" class, and there are some student object (for example 100):

class students:
    def __init__(self, name):
        self.name = name

Some of these students are special (for example five), now I want to define three variables z0, z1, z2 for each of these five special students:

for c in self.candidate_student:
   z0 
   z1 
   z2

After this part, I want to call each candidate student variable by name, like this:

student.name.z0
student.name.z1
student.name.z2

Can anyone explain how I can achieve this?

3
  • make name a class as well. Commented Jul 17, 2018 at 17:28
  • This appears to be a stereotypical application of subclass, using inheritance. Was that not in your learning materials? Commented Jul 17, 2018 at 18:01
  • What is this candidate_student attribute of students? How do you recognize which students are "special"? Do they still have all of the attributes of a typical student? Commented Jul 17, 2018 at 18:03

2 Answers 2

1

If you meant to define z0,z1 and z2 values for each of the 'special' students, you can set them as attributes of the object instances. Note you can add a new attribute to an object at any time, it doesn't have to be in the __init__() method. For example, if you are creating a new 'special student' object:

s = student("John Doe")
s.z0 = 7
s.z1 = 8
s.z2 = 9

Now, s just got three new attributes (besides name, which you set in __init__), you can address them like variables anywhere after they have been set. E.g., after the above:

print (s.name) # will print "John Doe"
print (s.z2) # will print 9

Note if you have code that works with both 'special' and 'non-special' objects, you should expect that the special attributes aren't always there (so if you try to use student.z0 on an object that didn't have that set beforehand, you will get an exception).

Sign up to request clarification or add additional context in comments.

1 Comment

Tnx so much! understand now! I thought like C base languages need to define all variables first, and I had problem with these special cases! but your answer was helpful :)
1

Since you want to add properties to your special students this code might help:

class students:
    def __init__(self, name, z=None):
        self.name = name
        self.z = z or []

You can initialize your special student like this:

ana = students('Ana', ['Apple', 'Ball', 'Pen'])

And call the properties like this:

ana.z[0]
ana.z[1]

3 Comments

I think it dosen't work for me. Assume 'Ana' is an student object and I want to read something like this : (Ana.z0 + Ana.Z1)
@sali, how about now?
It isn't wrong. but I wanted to create (z0 to z2) variables jussst for special cases! I think, I found my answer now with other comments. tax for your time :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.